Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

This lesson is for members only. Join us and get access to hundreds of tutorials and a community of expert Pythonistas.

Unlock This Lesson

Type Hinting

Give Feedback

In this lesson, you’ll learn about type hinting in Python. Type hinting is a formal solution to statically indicate the type of a value within your Python code. It was specified in PEP 484 and introduced in Python 3.5.

Here’s an example of adding type information to a function. You annotate the arguments and the return value:

def greet(name: str) -> str:
    return "Hello, " + name

The name: str syntax indicates the name argument should be of type str. The -> syntax indicates the greet() function will return a string.

The following example function turns a text string into a headline by adding proper capitalization and a decorative line:

>>>
>>> def headline(text, align=True):
...    if align:
...        return f"{text.title()}\n{'-' * len(text)}"
...    else:
...        return f" {text.title()} ".center(50, "o")
...
...
>>> print(headline("python type checking))
Python Type Checking
--------------------

>>> print(headline("python type checking", align=False))
oooooooooooooo Python Type Checking oooooooooooooo

Now add type hints by annotating the arguments and the return value as follows:

>>>
>>> def headline(text: str, align: bool = True) -> str:
...    if align:
...        return f"{text.title()}\n{'-' * len(text)}"
...    else:
...        return f" {text.title()} ".center(50, "o")
...
...
>>> headline
<function headline at 0x105b81268>

>>> print(headline("python type checking, align="left"))
Python Type Checking
--------------------

>>> print(headline("python type checking, align="center"))
Python Type Checking
--------------------

In terms of style, PEP 8 recommends the following:

  • Use normal rules for colons, that is, no space before and one space after a colon (text: str).
  • Use spaces around the = sign when combining an argument annotation with a default value (align: bool = True).
  • Use spaces around the -> arrow (def headline(...) -> str).

To learn more about f-strings, check out the following resources:

Comments & Discussion

Pygator on Nov. 3, 2019

I get that this may have it’s use, but i’ve seen other coding styles that imply what the arguments should be based on the docstring. I think that is another good alternative.

Geir Arne Hjelle RP Team on Nov. 3, 2019

I agree that using docstrings for types is a decent alternative for documentation purposes.

The main downside to only using docstrings is that it’s hard to automatically check types in docstrings, because there is no convention everybody follows. This is turn means that it’s hard for tools like static type checkers and IDEs to make use of those types.

Become a Member to join the conversation.