Skip to content
Home / Fundamentals

Python Typing module

In Python, typing is optional. This means that you don't have to specify the data type of a variable when you declare it, and the same goes for the return type of a function. However, Python does have a built-in module called typing that allows you to add type hints to your code.

The typing module provides several types that you can use as type hints. For example, you can use int to specify that a value should be an integer, or List to specify that a value should be a list.

To use the typing module, you will need to import it at the top of your file:

import typing

How do you add type hints?

To add a type hint to a variable or function argument, you specify the type after a colon :

age: int = 30
names: List[str] = ["Alice", "Bob", "Charlie"]

To add a type hint to a compound data type such as the names list variable above, you use the name of the type followed by brackets [] and the name of the value you want to type.

To specify that a function should return a value of a certain type, you use the same syntax, but after the function's arguments and before the ->. For example:

def add(x: int, y: int) -> int:
    return x + y

Here is another example that shows how to use type hints in a function definition:

def greet(name: str) -> str:
    return "Hello, " + name

In this example, the greet function takes a single argument name, which is a string, and returns a string.

Type hints can be provied in several places in your code:

  • in function arguments, to specify the type of the arguments being passed to the function
  • In the return statement of a function, to specify the return type of the function
  • In variables, to specify the type of the value being assigned to the variable

Best Practices

  • Use type hints consistently: It is a good idea to add type hints to all of your functions and variables, not just some of them. This will make it easier to understand your code and catch type errors.
  • Be specific: When specifying types, use the most specific type possible. For example, instead of using List for a list of integers, you could use List[int]. This will make it clearer to readers of your code what types of values are expected.
  • Don't rely on type hints for validation: Type hints are just hints, and they are not enforced at runtime. It is still a good idea to validate the types of your inputs and outputs in your code to ensure that they are correct.
  • Document your code: In addition to adding type hints, it is a good idea to add documentation to your code using docstrings or comments. This will help readers of your code understand what your functions and variables do and how to use them.