Questions tagged [mypy]

Mypy is an optional static type checker for Python.

Mypy is an optional static type checker for Python. Type hints conforming to PEP484 can be added to Python programs using Python's built-in type annotations (since Python 3) or a comment-based annotation syntax for Python 2.

2299 questions
32
votes
3 answers

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

mypy complains error: Variable "packagename.Foo" is not valid as a type Foo = type('Foo', (), {}) Bar = Optional[Foo] This error can be fixed by defining the type as a class: class Foo: pass Bar = Optional[Foo] Is there any other way around…
user3534080
  • 1,201
  • 1
  • 14
  • 21
32
votes
2 answers

A way to subclass NamedTuple for purposes of typechecking

I have several namedtuples that share some fields. I have a function that accepts these tuples and is guaranteed to only interact with the shared fields. I want to typecheck such code in mypy. An example of the code would be: from typing import…
wuzwm
  • 501
  • 1
  • 5
  • 11
30
votes
2 answers

Type hints for SQLAlchemy engine and session objects

I'm trying to add type hints to my SQLAlchemy script: connection_string: str = "sqlite:///:memory:" engine = create_engine(connection_string) session = Session(bind=engine) reveal_type(engine) reveal_type(session) I've ran this script against mypy…
Johnny Metz
  • 5,977
  • 18
  • 82
  • 146
30
votes
2 answers

Inherit generic type in python 3 with typing

I'm doing some experiments with typing in Python 3.6 and mypy. I want to design an entity class that can be instantiated in two ways: By the use of an ordinary initializer (p = Person(name='Hannes', age=27)) Statically from a state object (p =…
Hannes Petri
  • 864
  • 1
  • 7
  • 15
29
votes
2 answers

Type hinting sqlalchemy query result

I can't figure out what kind of object a sqlalchemy query returns. entries = session.query(Foo.id, Foo.date).all() The type of each object in entries seems to be sqlalchemy.util._collections.result, but a quick from sqlalchemy.util._collections…
JPFrancoia
  • 4,866
  • 10
  • 43
  • 73
28
votes
1 answer

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

I'm trying to Type Hint the function bar, but I got the Too few arguments error when I run mypy. from typing import Callable, Optional def foo(arg: int = 123) -> float: return arg+0.1 def bar(foo: Callable[[int], float], arg: Optional[int] =…
DonLarry
  • 702
  • 2
  • 11
  • 22
28
votes
1 answer

Return None from python function annotated with mypy, multiple return types

I come from a Typescript background. I'm bringing static type checking into a python project I'm working on (using mypy). In Typescript, it is valid to return null from a function that is annotated to return something else, i.e. a string: function…
Corey Cole
  • 2,262
  • 1
  • 26
  • 43
27
votes
1 answer

Specific type annotation for NumPy ndarray using mypy

Support for type annotations was added in NumPy 1.20. I'm trying to figure out how to tell mypy that an array is filled with elements of a particular type, the annotation np.ndarray[np.dcomplex] gives the mypy error "ndarray" expects no type…
John
  • 723
  • 1
  • 5
  • 12
27
votes
2 answers

Mypy error on dict of dict: Value of type "object" is not indexable

I have the following dictionary on python: dictionary = { 'key1': 1, 'sub_dict': {'key2': 0}, } When I run mypy on the following line: print(dictionary['sub_dict']['key2']) it raises the error Value of type "object" is not indexable
Pierre S.
  • 988
  • 1
  • 14
  • 20
25
votes
3 answers

What is the correct way to type hint a homogenous Queue in Python3.6 (especially for PyCharm)?

I'm writing a fractal generator in Python 3.6, and I use multiprocessing.Queues to pass messages from the main thread to the workers. This is what I've tried so far, but PyCharm doesn't seem to be able to infer attribute types for items taken from…
Broseph
  • 1,655
  • 1
  • 18
  • 38
24
votes
2 answers

Run mypy on all Python files of a project

How can I run mypy on all .py files in a project? I have seen I can specify a module to run mypy on but not something to specify a file mask or something like this.
Notbad
  • 5,936
  • 12
  • 54
  • 100
24
votes
2 answers

How to cast a typing.Union to one of its subtypes in Python?

I’m using Python 3.6.1, mypy, and the typing module. I created two custom types, Foo and Bar, and then used them in a dict I return from a function. The dict is described as mapping str to a Union of Foo and Bar. Then I want to use values from this…
Chris Warrick
  • 1,571
  • 1
  • 16
  • 27
24
votes
4 answers

Need type annotation for variable in python 3.5 code

I am using mypy on my python 3.5 code, and I got a lot of messages which look like this: file:line number: error: Need type annotation for variable But I read about the new features in python 3.6 that it introduced the syntax for variable…
Yuval Pruss
  • 8,716
  • 15
  • 42
  • 67
23
votes
1 answer

Is there a way to ignore mypy checks on a single function?

You can ignore mypy checks on a individual lines as answered here. Is there a way to ignore mypy for a full function?
Ananda
  • 2,925
  • 5
  • 22
  • 45
23
votes
2 answers

Exclude type in Python typing annotation

I wrote the following function: def _clean_dict(d): return {k: v for k, v in d.items() if v is not None} I want to add type annotations to the function: def _clean_dict(d: Dict[Any, Any]) -> Dict[Any, Any]: return…
Yam Mesicka
  • 6,243
  • 7
  • 45
  • 64