Type Hints and Defaults

Learn about the type hints, defaults, and docstring implementation in Python.

We’ve noted a few times now, hints are optional. They don’t do anything at runtime. There are tools; however, that can examine the hints to check for consistency. The mypy tool is widely used to check type hints.

Using default arguments

If we don’t want to make the two arguments required, we can use the same syntax Python functions use to provide default arguments. The keyword argument syntax appends an equals sign after each variable name. If the calling object does not provide this argument, then the default argument is used instead. The variables will still be available to the function, but they will have the values specified in the argument list. Here’s an example:

class Point:
    def __init__(self, x: float = 0, y: float = 0) -> None:
        self.move(x, y)

The definitions for the individual parameters can get long, leading to very long lines of code. In some examples, we’ll see this single logical line of code expanded to multiple physical lines. This relies on the way Python combines physical lines to match ()'s. We might write this when the line gets long:

Get hands-on with 1200+ tech skills courses.