Difference between defining typing.Dict and dict?

There is no real difference between using a plain typing.Dict and dict, no. However, typing.Dict is a Generic type * that lets you specify the type of the keys and values too, making it more flexible: def change_bandwidths(new_bandwidths: typing.Dict[str, str], user_id: int, user_name: str) -> bool: As such, it could well be that at some … Read more

Type hinting a collection of a specified type

Answering my own question; the TLDR answer is No Yes. Update 2 In September 2015, Python 3.5 was released with support for Type Hints and includes a new typing module. This allows for the specification of types contained within collections. As of November 2015, JetBrains PyCharm 5.0 fully supports Python 3.5 to include Type Hints … Read more

Python type hinting without cyclic imports

There isn’t a hugely elegant way to handle import cycles in general, I’m afraid. Your choices are to either redesign your code to remove the cyclic dependency, or if it isn’t feasible, do something like this: # some_file.py from typing import TYPE_CHECKING if TYPE_CHECKING: from main import Main class MyObject(object): def func2(self, some_param: ‘Main’): … … Read more

How to specify “nullable” return type with type hints

You’re looking for Optional. Since your return type can either be datetime (as returned from datetime.utcnow()) or None you should use Optional[datetime]: from typing import Optional def get_some_date(some_argument: int=None) -> Optional[datetime]: # as defined From the documentation on typing, Optional is shorthand for: Optional[X] is equivalent to Union[X, None]. where Union[X, Y] means a value … Read more

Type annotations for *args and **kwargs

For variable positional arguments (*args) and variable keyword arguments (**kw) you only need to specify the expected value for one such argument. From the Arbitrary argument lists and default argument values section of the Type Hints PEP: Arbitrary argument lists can as well be type annotated, so that the definition: def foo(*args: str, **kwds: int): … 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