[FIXED] Correct Type Annotation for objects generated by the functions from a library

Issue

I'm writing a function that requires engine from sqlalchemy.

The engine can be initialised in the following manner

import sqlalchemy
engine = sqlalchemy.create_engine(connection_str+ "schema_name")

I'm type hinting for engine as follows

from typing import Type
engine: Type[sqlalchemy.create_engine]

This doesn't give me any error when using mypy. However, I do get a note saying See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports. I read through that link but got even more confused.

Question. Is anything wrong with the type hinting that I have used?

EDIT

I created a test python file as follows

from typing import Type
from sqlalchemy.engine import Engine
import sqlalchemy  

engine: Engine = sqlalchemy.create_engine("mysql://root:password@localhost:3306")

However, I'm still getting error

test.py:2: error: Skipping analyzing "sqlalchemy.engine": module is installed, but missing library stubs or py.typed marker
test.py:3: error: Skipping analyzing "sqlalchemy": module is installed, but missing library stubs or py.typed marker
test.py:3: note: See https://mypy.readthedocs.io/en/stable/running_mypy.html#missing-imports
Found 2 errors in 1 file (checked 1 source file)

Solution

In the docstring of this function you can read

Create a new :class:_engine.Engine instance.

So the correct type is Engine.

import sqlalchemy
from sqlalchemy.engine import Engine

engine: Engine = sqlalchemy.create_engine()

SQLAlchemy is not statically typed, so it will leverage stub files with .pyi extension.

Dropbox org maintains sqlalchemy-stubs.

After installing stubs and adding them to your .mypy.ini config

[mypy]
plugins = sqlmypy

you should see no errors.

EDIT: Or, as @snakecharmerb pointed out in the comments, if you're using SQLA 1.4+ you might want to install official mypy stubs with

pip install sqlalchemy[mypy]

and add them to your mypy config

[mypy]
plugins = sqlalchemy.ext.mypy.plugin


Answered By - Tom Wojcik
Answer Checked By - Cary Denson (Python.Easybugfix Admin)

Related Posts

Post a Comment