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:
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.