Skip to content
The Chat Archive
Geminigemini-2.5-flash· Google LMArena Human Preference 140K

Is it possible to define a TypeVar in Python that me be assigned anything but a few…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Claudeclaude-sonnet-4-20250514’s answer.
  1. User

    Is it possible to define a TypeVar in Python that me be assigned anything but a few excluded types?

  2. Assistant

    No, not directly with TypeVar in Python's standard typing module.

    A TypeVar is designed to express inclusion or constraints on what types are allowed, not exclusion.

    Let's look at how TypeVar works:

    1. Unbounded: T = TypeVar('T') - This means T can be any type, including those you might want to exclude.
    2. Bounded: T = TypeVar('T', bound=SomeBaseClass) - This means T must be SomeBaseClass or a subclass thereof. This is an inclusion constraint.
    3. Constrained: T = TypeVar('T', str, int, float) - This means T must be one of str, int, or float. This is also an inclusion constraint (a union of allowed types).

    There is no excluded_types or not_bound_by parameter for TypeVar.

    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 int and str," what happens if someone passes Union[int, bool]? Is that allowed because it's not purely int or str? Or is it disallowed because it contains int? 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.

    1. Define a Protocol for what is allowed: If your function needs certain capabilities (e.g., it needs to be hashable, or have a name attribute), define a Protocol and bound your TypeVar to 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" protocol
      

      This is the most "Pythonic" static typing way to achieve something similar to exclusion by defining inclusion based on behavior.

    2. 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 Protocol or ABC, 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 runtime
      

      The type checker won't warn you if you call process_data(10) here because T is unconstrained. You'd typically use Any if you really mean "any type, but I'll validate at runtime."

    3. 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 TypeVar in Python's standard typing that directly expresses "anything but these specific types." You should instead define what your function can operate on (using Protocol or bound to an ABC) or use runtime validation for exclusions.

Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.