Skip to content
TheChatArchiveThe Chat Archive
Claudeclaude-sonnet-4-20250514· AnthropicHugging Face 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 Geminigemini-2.5-flash’s answer.
  1. User

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

  2. Claude 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.TypeVar with bound (Python 3.12+)

    The most direct approach uses the new bound parameter 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 value
    

    Practical 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 T as 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.

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