Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading