0

I have the following function:

def _init_db() -> "sqlalchemy.orm.session.Session":
    engine = create_engine("sqlite:///my_db.db")
    Base.metadata.create_all(engine)

    # Creating Session
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind = engine)
    session = Session()
    return session

Running mypy on the code gives me this error

error: Name 'sqlalchemy' is not defined

I tried with and without the quotes around sqlalchemy.orm.session.Session

How can I add type hints for sqlalchemy classes? What am I missing?

2 Answers 2

1

In order to use type hints you have import what you are trying to return. In first example I am trying to define a function returning some sqlite3 stuff without importing sqlite3. After I do import this module everything works fine.

In [1]: def init_db() -> sqlite3.Connection:
   ...:     return sqlite3.connection
   ...:
   ...:
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-1-b64a7629272c> in <module>()
----> 1 def init_db() -> sqlite3.Connection:
      2     return sqlite3.connection

NameError: name 'sqlite3' is not defined

In [2]: import sqlite3

In [3]: def init_db() -> sqlite3.Connection:
   ...:     return sqlite3.connection
   ...:
   ...:

In [4]:
Sign up to request clarification or add additional context in comments.

2 Comments

I added import sqlalchemy.orm.session.Session at the beginning of my script and got error: No library stub file for module 'sqlalchemy.orm.session.Session. So I guess there is no support for this class.
Add import sqlalchemy at the top or annotate only Session instead of the full path.
0

I got it thanks to gonczor's answer.

I needed to add

from sqlalchemy.orm.session import Session

at the beginning and then do

def _init_db() -> "Session":
    engine = create_engine("sqlite:///my_db.db")
    Base.metadata.create_all(engine)

    # Creating Session
    from sqlalchemy.orm import sessionmaker
    Session = sessionmaker(bind = engine)
    session = Session()
    return session

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.