Skip to content
TheChatArchiveThe Chat Archive
Mistralmistral-medium-2505· Mistral AIHugging Face LMArena Human Preference 140K

In Python I am subclassing from a generic class. To the sub-class I'd like to add…

From a Chatbot Arena battleThe same person sent this prompt to two anonymous models at once. Compare it with Geminigemini-2.5-pro’s answer.
  1. User

    In Python I am subclassing from a generic class. To the sub-class I'd like to add another Generic. May I do it like this:

    X = TypeVar("X") Y = TypeVar("Y") class Super(Base[X], Generic[Y]):

  2. Mistral Assistant

    In Python, when you're subclassing from a generic class and want to add another generic type parameter, your approach is almost correct, but there's a more conventional way to do it. Here's how you should structure it:

    from typing import Generic, TypeVar
    
    X = TypeVar("X")
    Y = TypeVar("Y")
    
    class Base(Generic[X]):
        pass
    
    class Super(Base[X], Generic[Y]):
        pass
    

    This is correct and will work as expected. However, there's a more common pattern where you combine all the generic parameters in a single Generic at the subclass level:

    class Super(Base[X], Generic[X, Y]):
        pass
    

    This second approach is often preferred because:

    1. It makes all generic parameters explicit in the subclass
    2. It's more consistent with how generic classes are typically defined
    3. It makes it clearer that the subclass is generic over both X and Y

    Both approaches are technically correct, but the second one is more conventional. The choice between them depends on whether you want to:

    • Keep X as inherited from the base class (first approach)
    • Explicitly declare all generic parameters in the subclass (second approach)

    If you're using Python 3.7+, you can also use the more concise syntax:

    class Super(Base[X], Generic[X, Y]):
        ...
    

    Or if you're using Python 3.12+, you can use the even simpler:

    class Super[X, Y](Base[X]):
        ...
    

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