Python Type Hints – *args and **kwargs (2021)

In this web content, the author discusses their initial confusion regarding Python’s variable argument operators (* and **) and how to properly use them when adding type hints. The author explains that * captures variable positional arguments in a tuple and ** captures variable keyword arguments in a dictionary. The author then explores the incorrect way of declaring the types of args and kwargs with type hints and highlights the errors that occur when running MyPy. The author then reveals the correct way of defining the types and emphasizes that * always binds to a tuple and ** always binds to a dict with string keys. They also reference PEP 484, which specifies the rule for annotating arbitrary argument lists. The author concludes by providing an example of correctly typed function and showcasing a successful type check.

To top