Skip to content

Python type alias

  • by

In Python, type aliases are used to create alternative names for existing data types. They are especially helpful for making your code more readable and for documenting the intent of certain variables or function parameters. Type aliases are introduced using the typing module, which provides various tools to work with types.

A type alias is defined by assigning the type to the alias:

Vector = List[float]

Here’s the correct way to define a type alias in Python:

from typing import List

# Define a type alias for a list of floats
Vector = List[float]

# Usage
vector1: Vector = [1.0, 2.0, 3.0]
vector2: Vector = [4.0, 5.0, 6.0]

print(vector1)  # Output: [1.0, 2.0, 3.0]
print(vector2)  # Output: [4.0, 5.0, 6.0]

In this example, we define the Vector type alias by directly assigning List[float] to it. The Vector type alias can now be used wherever we would use List[float], making the code more readable and expressive.

Python type alias example

You can use the NewType function from the typing module to create a type alias. Here’s an example using NewType:

from typing import NewType

# Define a type alias for a string representing a person's name
PersonName = NewType('PersonName', str)

# Use the type alias in function parameters
def greet_person(name: PersonName) -> str:
    return f"Hello, {name}!"

# Usage
name1 = PersonName("Alice")
name2 = PersonName("Bob")



Python type alias

In this example, we create the PersonName type alias using NewType. The first argument of NewType is the name of the new type ('PersonName'), and the second argument is the existing type it is based on (str).

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *