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
No, not directly with
TypeVarin Python's standardtypingmodule.A
TypeVaris designed to express inclusion or constraints on what types are allowed, not exclusion.Let's look at how
TypeVarworks:- Unbounded:
T = TypeVar('T')- This meansTcan be any type, including those you might want to exclude. - Bounded:
T = TypeVar('T', bound=SomeBaseClass)- This meansTmust beSomeBaseClassor a subclass thereof. This is an inclusion constraint. - Constrained:
T = TypeVar('T', str, int, float)- This meansTmust be one ofstr,int, orfloat. This is also an inclusion constraint (a union of allowed types).
There is no
excluded_typesornot_bound_byparameter forTypeVar.Why this is difficult/not directly supported:
- Type systems typically define what is allowed: It's much simpler and more robust to define the set of types that are valid rather than trying to define the infinite set of types that are not valid.
- Ambiguity: If you say "anything but
intandstr," what happens if someone passesUnion[int, bool]? Is that allowed because it's not purelyintorstr? Or is it disallowed because it containsint? This kind of logic gets complicated quickly.
How you might approach similar problems (workarounds and alternatives):
Since direct exclusion isn't possible, you generally have to flip your thinking to define what is allowed rather than what is excluded.
-
Define a
Protocolfor what is allowed: If your function needs certain capabilities (e.g., it needs to be hashable, or have anameattribute), define aProtocoland bound yourTypeVarto that protocol. This implicitly excludes types that don't conform.from typing import TypeVar, Protocol class HasName(Protocol): name: str T_HasName = TypeVar('T_HasName', bound=HasName) def greet_object(obj: T_HasName) -> str: return f"Hello, {obj.name}!" class User: def __init__(self, name: str): self.name = name class Car: # Does not have a 'name' attribute def __init__(self, make: str): self.make = make user = User("Alice") car = Car("Honda") number = 123 # Neither HasName nor a subclass print(greet_object(user)) # OK # greet_object(car) # Type checker error: "Car" does not satisfy "HasName" protocol # greet_object(number) # Type checker error: "int" does not satisfy "HasName" protocolThis is the most "Pythonic" static typing way to achieve something similar to exclusion by defining inclusion based on behavior.
-
Runtime Validation (if static checking isn't enough): If the exclusion is for runtime behavior that the type checker can't perfectly guarantee, or for types that don't fit a
ProtocolorABC, you'll need runtime checks.from typing import Any, TypeVar # T can still be anything from a type checker perspective, # but the runtime logic will enforce the exclusion. T = TypeVar('T') def process_data(data: T) -> T: if isinstance(data, (int, str)): # Exclude int and str at runtime raise TypeError(f"Type {type(data).__name__} is not allowed.") # ... do something with data ... return data process_data([1, 2, 3]) # OK process_data({'a': 1}) # OK # process_data(10) # Raises TypeError at runtime # process_data("hello")# Raises TypeError at runtimeThe type checker won't warn you if you call
process_data(10)here becauseTis unconstrained. You'd typically useAnyif you really mean "any type, but I'll validate at runtime." -
MyPy Plugins (Advanced/Specific): For very specific and complex scenarios, you could write a custom MyPy plugin that inspects types and reports errors based on exclusion rules. This is highly advanced, specific to MyPy (other type checkers might not support it), and requires significant effort. It's usually not worth it for most use cases.
In summary: You cannot define a
TypeVarin Python's standardtypingthat directly expresses "anything but these specific types." You should instead define what your function can operate on (usingProtocolorboundto anABC) or use runtime validation for exclusions. - Unbounded:
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.