Python equivalent of Typescript interface

For the code completion and type hinting in IDEs, just add static typing for the Person and Address classes and you are already good to go. Assuming you use the latest python3.6, here’s a rough equivalent of the typescript classes from your example: # spam.py from typing import Optional, Sequence class Address: street: str housenumber: … Read more

Proper type annotation of Python functions with yield

I figured out the answer on my own. I searched, but found no documentation for the 3 type parameters of Generator in the official typing documentation for Python 3.5.2 – beyond a truly cryptic mention of… class typing.Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]) Luckily, the original PEP484 (that started all this) was far more helpful: “The return … Read more

Python type hints and context managers

Whenever I’m not 100% sure what types a function accepts, I like to consult typeshed, which is the canonical repository of type hints for Python. Mypy directly bundles and uses typeshed to help it perform its typechecking, for example. We can find the stubs for contextlib here: https://github.com/python/typeshed/blob/master/stdlib/contextlib.pyi if sys.version_info >= (3, 2): class GeneratorContextManager(ContextManager[_T], … Read more

mypy, type hint: Union[float, int] -> is there a Number type?

Use float only, as int is implied in that type: def my_func(number: float): PEP 484 Type Hints specifically states that: Rather than requiring that users write import numbers and then use numbers.Float etc., this PEP proposes a straightforward shortcut that is almost as effective: when an argument is annotated as having type float, an argument … 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

How can I specify the function type in my type hints?

As @jonrsharpe noted in a comment, this can be done with typing.Callable: from typing import Callable def my_function(func: Callable): Note: Callable on its own is equivalent to Callable[…, Any]. Such a Callable takes any number and type of arguments (…) and returns a value of any type (Any). If this is too unconstrained, one may … Read more

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