Chapter 5: Advanced Python type features

Type hinting

face Josiah Wang

In this last chapter of the lesson, we will take a look at some advanced Python features loosely related to OOP. You probably do not even need these features most of the time, but it’s good to know they exist!

Recall that Python is a dynamically typed language, and so variables are not bound to any specific type. Compared to statically typed languages like C++ and Java, it reduces you having to be too obsessed about the type of a variable, allowing you to focus on solving problems instead.

Having said that, sometimes it might be helpful to have some hints about the expected type of a variable, for example in a function definition. You can of course include these in the docstrings, but perhaps it might be useful to have this information in the function definition itself?

Python 3.5 introduces a type hinting feature to annotate your functions with the expected type of the input parameters, as well as the type of the return value. Hopefully the following code is self-explanatory!

def greet(username: str, visits: int = 0) -> str:
    return f"Greetings, {username}. You have visited us {visits} times."

In addition to acting as documentation, you can also use a Python static type checker like MyPy to make sure that the types are valid in your code. This may help improve the stability of your code, as it can check for any unexpected types in your code.

I will not cover any more on the topic. The official documentation gives detailed examples and descriptions of many type hinting features available, so feel free to explore in your own time if you are interested in the topic.