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

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

Why is type hinting necessary in PHP?

Type hinting isn’t required, but it can allow you to catch certain types of mistakes. For example, you might have a function or method which requires an integer. PHP will happily convert “number looking strings” into integers, and this can cause hard to debug behaviour. If you specify in your code that you specifically need … 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

How to annotate function that takes a tuple of variable length? (variadic tuple type annotation)

We can annotate variable-length homogeneous tuples using the … literal (aka Ellipsis) like this: def process_tuple(t: Tuple[str, …]): … or for Python3.9+ def process_tuple(t: tuple[str, …]): … After that, the errors should go away. From the docs: To specify a variable-length tuple of homogeneous type, use literal ellipsis, e.g. Tuple[int, …]. A plain Tuple is … Read more