Type hints for SQLAlchemy engine and session objects

Figured it out: connection_string: str = “sqlite:///:memory:” engine = create_engine(connection_string) session = Session(bind=engine) print(type(engine)) # sqlalchemy.engine.base.Engine print(type(session)) # sqlalchemy.orm.session.Session Thus, type hinting is achieved the following way for example: from sqlalchemy.engine.base import Engine def test_func(engine: Engine): pass

Specific type annotation for NumPy ndarray using mypy

What you are looking for is the numpy.typing.NDArray class: https://numpy.org/doc/stable/reference/typing.html#numpy.typing.NDArray numpy.typing.NDArray[A] is an alias for numpy.ndarray[Any, numpy.dtype[A]]: import numpy as np import numpy.typing as npt a: npt.NDArray[np.complex64] = np.zeros((3, 3), dtype=np.complex64) # reveal_type(a) # -> numpy.ndarray[Any, numpy.dtype[numpy.complexfloating[numpy.typing._32Bit, numpy.typing._32Bit]]] print(a) prints [[0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j] [0.+0.j 0.+0.j 0.+0.j]] Note that even though you annotate … Read more

mypy “is not valid as a type” for types constructed with `type()`

How about this, as a workaround? from typing import Optional, TYPE_CHECKING if TYPE_CHECKING: class Foo: pass else: Foo = type(‘Foo’, (), {}) Bar = Optional[Foo] typing.TYPE_CHECKING is a constant that will always be True at compile-time, and will always be False at runtime. In this way, we can keep MyPy happy by only telling it … Read more

A way to subclass NamedTuple for purposes of typechecking

The way named tuples are constructed make inheritance from typing.NamedTuple classes as yet not possible. You’d have to write your own metaclass to extend the typing.NamedTupleMeta class to make subclassing work, and even then the class generated by collections.namedtuple() is just not built to extend. Instead, you want to use the new dataclasses module to … Read more

How to type hint a Callable of a function with default arguments?

Define this: class Foo(Protocol): def __call__(self, x: int = …, /) -> float: … then type hint foo as Foo instead of Callable[[int], float]. Callback protocols allow you to: define flexible callback types that are hard (or even impossible) to express using the Callable[…] syntax and optional arguments are one of those impossible things to … Read more

Define a jsonable type using mypy / PEP-526

Long story short, you have the following options: If you have zero idea how your JSON is structured and must support arbitrary JSON blobs, you can: Wait for mypy to support recursive types. If you can’t wait, just use object or Dict[str, object]. It ends up being nearly identical to using recursive types in practice. … Read more

Mypy does not respect setting in mypy.ini to exclude folder from checking when called from VS Code

The issue is that VS Code is invoking mypy file by file. And mypy doesn’t use the exclude option when invoked on a single file. The workaround is using python.linting.ignorePatterns in the settings.json. “python.linting.ignorePatterns”: [ “venv/**/*.py” ] More info about the behaviour of exclude: Note that this flag only affects recursive discovery, that is, when … Read more

Using the class’s own type inside class definition [duplicate]

When Foo.__eq__ is being defined the name Foo is still unbound, because the class itself hasn’t yet been created. Remember: function arguments are evaluated at function definition time, not at function call time. From Python 3.7+ you can postpone evaluation of annotations by adding this import at the top of the module: from __future__ import … Read more

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)