How to Add Types to Function Parameters/Signatures in Python
1 min readAug 31, 2022
The aim of this explainer💡 is to show how you designate a return type in Python. This arrived with Python 3.5 (2014) via PEP 484 — Type Hints.
Note that these are purely hints not a type checker. If looking for a type checker, check out mypy — Optional Static Typing for Python
- Without hints you would write
def greeting(name):
return 'Hello, {}'.format(name)
- Can now be written as this, utilizing also f-strings that arrived in 3.6 including the syntax for providing a default argument value for the
name
parameter
def greeting(name: str = "Mr Foo Bar") -> str:
return "Hello {name}"
- This is powerful mainly for custom types, this is how I initialize CLI argument parser making it clear what type of object the function returns
def init_argparse() -> argparse.ArgumentParser:
parser = argparse.ArgumentParser()
parser.add_argument("--param1")
parser.add_argument("--param2")
return parser