What is the type hint for a (any) python module?

and types.ModuleType() is a constructor. That doesn’t matter. types.ModuleType is still a reference to a type, just like str and int are. There is no need for a generic Module[typehint] annotation, so types.ModuleType is exacly what you need to use here. For example, the official Python typeshed project provides a type hint annotation for sys.modules … Read more

Weird MRO result when inheriting directly from typing.NamedTuple

This is because typing.NamedTuple is not really a proper type. It is a class. But its singular purpose is to take advantage of meta-class magic to give you a convenient nice way to define named-tuple types. And named-tuples derive from tuple directly. Note, unlike most other classes, from typing import NamedTuple class Foo(NamedTuple): pass print(isinstance(Foo(), … Read more

How to type hint a dictionary with values of different types

You are looking for TypedDict. It is currently only a mypy-only extension, but there are plans to make it an officially sanctioned type in the near-future. I am not sure if PyCharm supports this feature yet, though. So, in your case, you’d do: from mypy_extensions import TypedDict RectangleElements = TypedDict(‘RectangleElements’, { ‘front’: Line, ‘left’: Line, … Read more

Python type hint for classes that support __getitem__

If you’re willing to install a not-quite-offical extension to typing, typing-extensions, you can use a Protocol, which should be an implementation of PEP-0544: from typing_extensions import Protocol from typing import Any class GetItem(Protocol): def __getitem__(self: ‘Getitem’, key: Any) -> Any: pass class BadGetItem: def __getitem__(self, a: int, b: int) -> Any: pass def do_thing(arg: GetItem): … Read more

typing.Any vs object?

Yes, there is a difference. Although in Python 3, all objects are instances of object, including object itself, only Any documents that the return value should be disregarded by the typechecker. The Any type docstring states that object is a subclass of Any and vice-versa: >>> import typing >>> print(typing.Any.__doc__) Special type indicating an unconstrained … Read more