Is it possible to define a TypeVar in Python that me be assigned anything but a few…
- User
Is it possible to define a TypeVar in Python that me be assigned anything but a few excluded types?
Assistant
Yes, you can create a TypeVar that excludes specific types, though the approach depends on your Python version and specific needs.
Using
typing_extensions.TypeVarwithbound(Python 3.12+)The most direct approach uses the new
boundparameter that accepts unions:from typing import Union from typing_extensions import TypeVar # Exclude int and str T = TypeVar('T', bound=object) # This doesn't directly exclude types # Better approach - define what you DO want AllowedTypes = Union[float, list, dict, bool] # etc. T = TypeVar('T', bound=AllowedTypes)Using Protocol for Complex Exclusions
For more sophisticated exclusions, you can define a Protocol that describes what you want:
from typing import Protocol, TypeVar, runtime_checkable @runtime_checkable class NotIntOrStr(Protocol): def __hash__(self) -> int: ... # Most objects have this # Then use type intersection (Python 3.10+) from typing import TypeVar T = TypeVar('T', bound=NotIntOrStr) def my_function(value: T) -> T: if isinstance(value, (int, str)): raise TypeError("int and str not allowed") return valuePractical Runtime Checking
Often the cleanest approach combines TypeVar with runtime validation:
from typing import TypeVar, Type, Any T = TypeVar('T') EXCLUDED_TYPES = (int, str) def create_instance(cls: Type[T], *args: Any) -> T: if issubclass(cls, EXCLUDED_TYPES): raise TypeError(f"Type {cls} is not allowed") return cls(*args)The type system will still see
Tas unrestricted, but you get runtime safety. For static analysis, you'd need to use type: ignore comments or more complex type definitions depending on your specific use case.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.