Specify Desired Type
In this step, we will explore how to specify the desired type for variables and function arguments, and how to enforce these types using type hints and conditional checks. While Python is dynamically typed, type hints allow you to add static type information to your code, which can be used by type checkers like mypy
to catch type errors before runtime.
Type hints are annotations that specify the expected type of a variable, function argument, or function return value. They are written using the :
syntax for variables and arguments, and the ->
syntax for return values.
Let's start by adding type hints to our previous example.
-
Open the VS Code editor in the LabEx environment.
-
Create a new file named type_hints.py
in the ~/project
directory.
~/project/type_hints.py
-
Add the following code to type_hints.py
:
def add_numbers(x: int, y: int) -> int:
"""Adds two numbers together."""
return x + y
## Example usage
result: int = add_numbers(5, 3)
print(f"Result: {result}")
## Example with incorrect types
## This will not raise an error at runtime, but a type checker will flag it
## result: int = add_numbers("5", "3")
## print(f"Result: {result}")
In this script:
x: int
and y: int
specify that the arguments x
and y
should be integers.
-> int
specifies that the function add_numbers
should return an integer.
result: int
specifies that the variable result
should be an integer.
-
Run the script using the python
command in the terminal:
python ~/project/type_hints.py
You should see output similar to the following:
Result: 8
The script runs without errors because the types are correct. However, if you uncomment the lines with incorrect types, the script will still run, but a type checker like mypy
would flag these lines as type errors.
To install and run mypy
, you can use the following commands:
pip install mypy
mypy ~/project/type_hints.py
Since pip
is not pre-configured, you may encounter errors related to missing packages or incorrect versions. For the purpose of this lab, we will focus on demonstrating the concept of type hints and conditional checks.
Another way to enforce types is to use conditional checks within your code. This allows you to raise exceptions if the types are not what you expect.
def divide_numbers(x, y):
if not isinstance(x, (int, float)):
raise TypeError("x must be a number")
if not isinstance(y, (int, float)):
raise TypeError("y must be a number")
if y == 0:
raise ValueError("y cannot be zero")
return x / y
## Example usage
result = divide_numbers(10, 2)
print(f"Result: {result}")
## Example with incorrect types
## This will raise a TypeError
## result = divide_numbers("10", 2)
## print(f"Result: {result}")
In this example, we use isinstance()
to check if x
and y
are numbers (either int
or float
). If they are not, we raise a TypeError
. We also check if y
is zero and raise a ValueError
if it is.
By combining type hints and conditional checks, you can write more robust and maintainable Python code that is less prone to type errors.