Types in Python
This article explains types in Python.
YouTube Video
Types in Python
The typing
module in Python is used to introduce type hints into Python. It was originally introduced in Python 3.5 and is used to improve code readability and maintainability. Type hints do not affect the runtime of the code but allow for type checking with IDEs and static analysis tools.
Basics of Type Hints
Type hints clarify the intent of the code by explicitly specifying the types of functions and variables. In the example below, types are specified for the arguments and return value.
1def add_numbers(a: int, b: int) -> int:
2 return a + b
3
4result: int = add_numbers(5, 10)
5print(result) # 15
In the above code, a
and b
are of the integer type (int
), and the return value of the function is also explicitly stated as an integer. Even with type hints, types are not strictly enforced, but warnings may be displayed during development if there are type mismatches.
Key Type Hints
The typing
module in Python provides various classes and functions to define type hints. Below is a list of common type hints.
int
: integerstr
: stringfloat
: floating-point numberbool
: booleanList
: listDict
: dictionaryTuple
: tupleSet
: set
List
type
The list type is specified using the List
class. You can also explicitly specify the type of elements within a list.
1from typing import List
2
3def sum_list(numbers: List[int]) -> int:
4 return sum(numbers)
5
6print(sum_list([1, 2, 3])) # 6
In this example, all elements of the list are expected to be of type int
.
Dict
Type
A dictionary type is defined using Dict
. The types of keys and values can be specified.
1from typing import Dict
2
3def get_student_age(students: Dict[str, int], name: str) -> int:
4 return students.get(name, 0)
5
6students = {"Alice": 23, "Bob": 19}
7print(get_student_age(students, "Alice")) # 23
In this example, the dictionary uses str
as the key type and int
as the value type.
Tuple
Type
Tuples are specified using the Tuple
type. You can specify the type of each element in a tuple individually.
1from typing import Tuple
2
3def get_person() -> Tuple[str, int]:
4 return "Alice", 30
5
6name, age = get_person()
7print(name, age) # Alice 30
Here, the get_person
function is shown returning a tuple containing a string and an integer.
Union
Type
The Union
type is used to explicitly indicate that multiple types are acceptable.
1from typing import Union
2
3def process_value(value: Union[int, float]) -> float:
4 return value * 2.0
5
6print(process_value(10)) # 20.0
7print(process_value(3.5)) # 7.0
In this example, the process_value
function takes either an int
or float
as an argument and returns a result of type float
.
Optional
Type
The Optional
type is used when a variable might be None
. It is provided as a shorthand for Union[Type, None]
.
1from typing import Optional
2
3def greet(name: Optional[str] = None) -> str:
4 if name is None:
5 return "Hello, Guest!"
6 return f"Hello, {name}!"
7
8print(greet()) # Hello, Guest!
9print(greet("Alice")) # Hello, Alice!
Here, it shows that when name
is not specified, it is treated as None
.
Generic Types
Generic types are a way to abstractly represent what type of elements a data structure contains. In the typing
module, you can define generic types using TypeVar
.
1from typing import TypeVar, List
2
3T = TypeVar('T')
4
5def get_first_element(elements: List[T]) -> T:
6 return elements[0]
7
8print(get_first_element([1, 2, 3])) # 1
9print(get_first_element(["a", "b", "c"])) # a
In this example, get_first_element
is a function that returns the first element of a list, and it works regardless of the list's type.
Type Aliases
A type alias is a way to simplify complex type definitions by giving them a clear name.
1from typing import List, Tuple
2
3Coordinates = List[Tuple[int, int]]
4
5def get_coordinates() -> Coordinates:
6 return [(0, 0), (1, 1), (2, 2)]
7
8print(get_coordinates()) # [(0, 0), (1, 1), (2, 2)]
In this example, a type alias Coordinates
is defined to simply represent a type with tuples inside a list.
Summary
The typing
module in Python is very useful for improving the readability and maintainability of code. By properly utilizing type hints, you can help prevent type mismatches and bugs, especially in large-scale projects or team development. Types are merely a development support tool and do not affect runtime behavior, thus maintaining code flexibility.
You can follow along with the above article using Visual Studio Code on our YouTube channel. Please also check out the YouTube channel.