
Code
Label the Crates
A type hint (or annotation) is a label saying what type a value
should be. Parameters get : type, and the return value gets
-> type:
def greet(name: str, times: int = 1) -> str:
return ("Hi " + name + "! ") * times
lanterns: int = 12 # variables can be annotated too
Why bother?
- Readers instantly know what to pass and what comes back.
- Editors autocomplete better and warn about mistakes as you type.
- Type checkers like
mypyorpyrightscan a whole project and catch bugs (like passing astrwhere anintbelongs) before the code even runs.
Python stores the hints on the function, so tools can read them:
from typing import get_type_hints
print(get_type_hints(greet))
# {'name': <class 'str'>, 'times': <class 'int'>, 'return': <class 'str'>}
Pip tip: A function that returns nothing is annotated
-> None.
Assignment
The two functions already work. Add type hints:
fuel_cost:litersandprice_per_literarefloat, and it returns afloat.lantern_label:nameis astr,countis anint(keep the default1), and it returns astr.
The two functions already work. Add type hints:
fuel_cost:litersandprice_per_literarefloat, and it returns afloat.lantern_label:nameis astr,countis anint(keep the default1), and it returns astr.
main.py Python sleeping
Press Run to try your code, then Check to test it.