2

SQLAlchemy session not working when I use it inside a with statement. It should work, since the sessionmaker returns a Session object that according to the source code does have __enter__ and __exit__ methods. I checked and I am in using the latest version (SQLAlchemy==1.3.22).

Code used to pinpoint the error:

from sqlalchemy import create_engine
from sqlalchemy.orm import sessionmaker

engine = create_engine(
    'sqlite:////devdb/sqlite.db',
    echo=True
)

Session = sessionmaker(bind=engine)

with Session() as session:
    print('it worked!')

The Error:

Traceback (most recent call last):
  File "test.py", line 11, in <module>
    with Session() as session:
AttributeError: __enter__

I also tried my own class, just to test it, and same error occurred:

class MySessionMaker(sessionmaker):
    def __init__(self, bind):
        super().__init__(bind=bind)

    def __enter__(self):
        return self()

    def __exit__(self, exception_type, exception_value, exception_traceback):
        self.close()



Session = MySessionMaker(bind=engine)

I could not find anything online regarding this error, have anyone else encountered this problem?

double-beep
  • 5,031
  • 17
  • 33
  • 41
LombardiD
  • 301
  • 1
  • 2
  • 9
  • One case might be that you've assigned the built-in `Session` to something else in your code. Please check that. – Mayank Porwal Apr 05 '21 at 18:24
  • the code I posted is the complete file that gives me the error – LombardiD Apr 05 '21 at 18:28
  • Did you ever figure this out? I am having the same problem. – Spencer Oct 27 '21 at 22:36
  • @SpencerBoucher it was an issue with some module's version, i just recreated the env with the latest stable versions and it worked. – LombardiD Oct 28 '21 at 00:42
  • 1
    Does this answer your question? [Receiving "AttributeError: \_\_enter\_\_" when using SQLAlchemy Session as context manager](https://stackoverflow.com/questions/66554373/receiving-attributeerror-enter-when-using-sqlalchemy-session-as-context-m) – swimmer Jan 17 '22 at 11:27

0 Answers0