dev0928
Posted on April 24, 2021
Python is a dynamically typed language. This means we don’t need to explicitly specify the type of a variable while declaring it. Python runtime engine infers variables' data type based on the value assigned to them. Here are few examples:
greeting = ‘hello’
print(type(greeting)) # <class 'str'>
count = 10
print(type(count)) # <class 'int'>
Even though the above way of declaration makes the code more concise, it is prone to type errors if the application being developed has a large number of modules and classes.
What are type hints?
Typing module introduced in Python 3.5 supports declaration of type hints to variables and function return types. Although Python runtime does not enforce variable and function return type annotations, these type hints can be used by Integrated Development Environments (IDEs) and type checkers to enforce static types. Thereby reducing bugs early during the development process.
Examples
from typing import List, Optional
def sum_nunbers(num1: int, num2: int) -> int:
return num1 + num2
def get_square_list(max_num: int) -> List[int]:
return [n * n for n in range(max_num)]
# An argument could be explicitly marked optional using below type hint
def create_greeting(name: Optional[str] = 'World') -> str:
return f"Hello, {name}"
print(sum_nunbers(10, 20)) # 30
print(get_square_list(5)) # [0, 1, 4, 9, 16]
print(create_greeting('Joe')) # Hello, Joe
print(create_greeting()) # Hello, World
Benefits of type hints
- Type hints serve as a great documentation in larger applications
- These type declarations could help uncover some of the type errors with the help of IDEs and type checkers
Further Learning
Although, type hints may be overkill for small experimental Python modules, they would be much more useful in a larger application. I think type hints if used consistently would help promote clean code that is easier to understand. To learn more visit - https://docs.python.org/3/library/typing.html
Posted on April 24, 2021
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.