python: Getting the generic class of a base class, from a subclass class method

Viewed 33

Bar is derived from BaseBare[Foo]. And Foo is derived from BaseFoo. I want to call the class method bar which calls the class method foo from Foo. I found a hack using get_args, but I don't think this is the right way, as the index 0 can change depending on the ordering of the parent Generic[FOO], X,Y

from abc import abstractmethod
from typing import TypeVar, Generic, get_args

class X:
    pass

class Y:
    pass

class BaseFoo:

    @classmethod
    @abstractmethod
    def foo(cls):
        raise NotImplementedError


class Foo1(BaseFoo):

    @classmethod    
    def foo(cls):
        print("foo1")


class Foo2(BaseFoo):

    @classmethod
    def foo(cls):
        print("foo2")


FOO = TypeVar('FOO', bound=BaseFoo)


class BaseBar(Generic[FOO], X, Y): # ordering matters here since we use get_args

    @classmethod
    def bar(cls):
        # hack to get the generic class FOO of the BaseBar's subclass
        foo_cls = get_args(cls.__orig_bases__[0])[0]
        foo_cls.foo()


class Bar1(BaseBar[Foo1]):
    pass


class Bar2(BaseBar[Foo2]):
    pass


Bar1.bar() # foo1
Bar2.bar() # foo2
0 Answers
Related