Python type annotations multiple types

Stewart 44 Published: 11/10/2024

Python type annotations multiple types

I'll respond in English as per your request. Now, let's dive into the world of type annotations in Python!

Python 3.5 introduced a new feature called "Type Hints" or "Type Annotations", which allows developers to specify the expected data type for a variable, function parameter, or return value. This feature is not enforced by default and only serves as a documentation tool. However, tools like mypy can be used to check the types at runtime.

Multiple Types

Python supports multiple types in type annotations using tuples. When you want to define a function that can accept different types of input, you can use tuples to specify multiple types. Here's an example:

def greet(name: str | int) -> None:

print(f"Hello, {name}!")

In this example, the greet function accepts either a string or an integer as its argument and returns nothing (None). You can call this function with a string like "John" or an integer like 1.

You can also use multiple types in function return values. For instance:

def get_user_input() -> str | int:

user_input = input("Enter something: ")

if user_input.isdigit():

return int(user_input)

else:

return user_input

This get_user_input function prompts the user to enter some text and then tries to convert that input into an integer. If it can be converted, the function returns the integer; otherwise, it returns the original string.

Another use case for multiple types is when you want a function to accept a specific type of object as an argument. For example:

from dataclasses import dataclass

@dataclass

class Person:

name: str

age: int

def process_person(person: Person | dict) -> None:

if isinstance(person, dict):

person = Person(**person)

print(f"Hello, {person.name}! You are {person.age} years old.")

In this example, the process_person function accepts either a Person object or a dictionary that represents a Person. It then extracts the name and age from the input and prints out a greeting message.

Python's multiple types feature provides more flexibility when defining function signatures. You can specify multiple possible types for function arguments, return values, or even both! This helps make your code more robust and self-documenting.

In conclusion, Python's type annotation feature is a powerful tool that enables developers to specify the expected data type for variables, function parameters, and return values. By using tuples to define multiple types, you can create functions with more flexible input and output requirements. This can lead to cleaner, more maintainable code that's easier to understand and debug.

Python type annotations list

Here is a comprehensive list of Python type annotations:

Basic Types

int: An integer value (e.g., 42) float: A floating-point number (e.g., 3.14) str: A string literal (e.g., "hello") bool: A boolean value (e.g., True or False)

Container Types

list[T]: A list of values of type T (e.g., [1, 2, 3]) tuple[T]: A tuple of values of type T (e.g., (1, 2, 3)) dict[K, V]: A dictionary with keys of type K and values of type V (e.g., {a: 1, b: 2}) set[T]: A set of unique values of type T (e.g., {1, 2, 3})

Complex Types

NoneType: The None type (i.e., the absence of a value) class: A class instance function: A function object type: A type object (used for meta-programming)

Specialized Types

Any: A special type that represents any Python object Union[T, U]: A union of types T and U Optional[T]: A type that may be either T or None Literal[S]: A type that is a literal value from the set S

Type Variants

List[T] (equivalent to list[T]) Tuple[T, ...] (equivalent to tuple[T, ...]) Dict[K, V] (equivalent to dict[K, V]) Set[T] (equivalent to set[T])

Type Constructions

-> T: Returns a value of type T [T] -> R: Takes a list of values of type T and returns a value of type R (T, U) -> R: Takes two values of types T and U and returns a value of type R

Type Constraints

assert isinstance(x, T): Ensures that x is an instance of class T assert isinstance(x, (T, U)): Ensures that x is an instance of either class T or class U assert not isinstance(x, T): Ensures that x is not an instance of class T

Type-related Functions

isinstance(x, T): Returns True if x is an instance of class T issubclass(T, U): Returns True if class T is a subclass of class U typing.get_type_hints(obj): Returns the type hints for object obj

Type-related Errors

TypeError: Raised when a type error occurs (e.g., trying to use an integer where a string is expected) ValueError: Raised when a value error occurs (e.g., trying to convert None to an integer)

This list should cover most of the Python type annotations you need to know. Happy coding!