Middle+
How to improve the type annotation of a dictionary flip function to show that keys and values are swapped? What is TypeVar?
sobes.tech AI
Answer from AI
To annotate a function that unpacks a dictionary by swapping keys and values, you can use two type parameters with TypeVar. This allows explicitly specifying that the types of keys and values are swapped.
Example:
from typing import TypeVar, Dict
K = TypeVar('K') # Type of the original dictionary's keys
V = TypeVar('V') # Type of the original dictionary's values
def invert_dict(d: Dict[K, V]) -> Dict[V, K]:
return {v: k for k, v in d.items()}
Here, TypeVar is a way to declare a type parameter that can be any type but maintains the relationship between input and output types. This makes the annotation more flexible and precise, especially in generic functions and classes.