Type hints are a feature in Python that allow developers to annotate their code with expected types for variables and function arguments. This helps to improve code readability and provides an opportunity to catch errors before runtime using type checkers like mypy.
Using Type Hints in Python
1. Variable and Function Type Hints
Type hints define the expected type for variables and function arguments. Example:
Python
age: int = 25
def greet(name: str) -> str:
return f"Hello, {name}!"
Explanation:
- age is an integer (int).
- greet function expects a string (name: str) and returns a string (-> str).
2. Function Return Type
The return type of a function can be specified using ->. Example:
Python
def add_numbers(x: int, y: int) -> int:
return x + y
Explanation: The add_numbers function expects two integers (x: int, y: int) and returns an integer (-> int).
3. Optional Types and Collections
Use Optional for values that can be None, and define types for collections like lists and tuples. Example:
Python
from typing import Optional, List, Tuple
def get_user(id: int) -> Optional[str]:
return None if id == 0 else "User"
def sum(num: List[int]) -> int:
return sum(num)
def get_name_and_age() -> Tuple[str, int]:
return ("Abc", 25)
Explanation:
- Optional[str]: The get_user function can return either a string or None.
- List[int]: The sum_numbers function expects a list of integers.
- Tuple[str, int]: The get_name_and_age function returns a tuple with a string and an integer.
Example Without Type Hints
Here’s an example of a factorial function without type hints:
Python
def factorial(i):
if i < 0:
return None
if i == 0:
return 1
return i * factorial(i - 1)
print(factorial(4))
print(factorial("4"))
print(factorial(5.01))
Output
Output without Type HintsExplanation:
- The function works fine with integers.
- It throws an error if a string is passed (since you cannot perform mathematical operations on strings).
- It also throws an error with floating-point numbers. For instance, passing 5.01 will eventually lead to an issue where the function tries to decrement the number until it reaches a non-integer value, causing it to return None and break the logic.
Adding Type Hints
By adding type hints, we can make the function’s expected behavior more clear. Here’s the modified code with type hints:
Python
def factorial(i: int) -> int:
if not isinstance(i, int):
return None
if i < 0:
return None
if i == 0:
return 1
return i * factorial(i - 1)
print(factorial(5.01))
Explanation: In this version, if the input isn't an integer, the function will return None instead of causing an error.
Why Type Hints Don’t Prevent Errors
Type hints are not enforced by the Python interpreter; they are purely for static analysis by external tools like mypy. So, even with type hints, the code will still run with errors unless a static type checker is used. Python won’t prevent you from passing a string or floating-point number to the function at runtime.
Using mypy for Type Checking
To actually check if your code violates any type hints, you can use a tool like mypy, a static type checker for Python. Running mypy on your script will not execute the code but will analyze it for type hint violations. For example, let's check the factorial function with mypy:
1. Install mypy: If you don't have mypy installed, you can install it using pip:
pip install mypy
2. Run mypy on your script: Now, you can run the following command:
mypy ranking.py
This will analyze your code and give a clear error message if the types don’t match, like:
Error Message
Similar Reads
type() function in Python The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
type() function in Python The type() function is mostly used for debugging purposes. Two different types of arguments can be passed to type() function, single and three arguments. If a single argument type(obj) is passed, it returns the type of the given object. If three argument types (object, bases, dict) are passed, it re
5 min read
Type Conversion in Python Python defines type conversion functions to directly convert one data type to another which is useful in day-to-day and competitive programming. This article is aimed at providing information about certain conversion functions. There are two types of Type Conversion in Python: Python Implicit Type C
5 min read
Types of Arguments in Python Arguments are the values passed inside the parenthesis of the function. A function can have any number of arguments separated by a comma. There are many types of arguments in Python .In this example, we will create a simple function in Python to check whether the number passed as an argument to the
3 min read
Self Type in Python Self-type is a brand-new function added to Python 3.11. A method or function that returns an instance of the class it belongs to is defined by the self type. In situations where we wish to enforce that a method returns an instance of the class and not some other type, self-type is beneficial. Return
2 min read
Python Data Types Python Data types are the classification or categorization of data items. It represents the kind of value that tells what operations can be performed on a particular data. Since everything is an object in Python programming, Python data types are classes and variables are instances (objects) of thes
9 min read