How to declare TypeVar as immutable

46 Views Asked by At

In Python, how do I make an immutable/mutable type variable. I have a generic protocol, and some of its methods ought to mutate its inputs of variadic type, while some should not. How do I declare this in my code?

1

There are 1 best solutions below

0
Bob Robertson On

For immutable data classes you can use:

from typing import TypeVar
from dataclasses import dataclass

T = TypeVar('T')

@dataclass(frozen=True)
class ImmutableGenericClass:
    value: T

# Example usage:
int_item = ImmutableGenericClass[int](value=1)
str_item = ImmutableGenericClass[str](value="example")

For immutability with type hints in general, try:

from typing import NamedTuple, TypeVar

T = TypeVar('T')

class ImmutableGenericTuple(NamedTuple):
    value: T

# Example usage:
int_item = ImmutableGenericTuple[int](value=1)
str_item = ImmutableGenericTuple[str](value="example")