langlauf.io
langlauf.io

Reputation: 3191

mypy and sqlalchemy: error: Name 'sqlalchemy' is not defined

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?

Upvotes: 0

Views: 2561

Answers (2)

langlauf.io
langlauf.io

Reputation: 3191

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

Upvotes: 0

gonczor
gonczor

Reputation: 4146

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]:

Upvotes: 1

Related Questions