shadowtalker
shadowtalker

Reputation: 13823

How to hint that a variable is a class inheriting from another class?

Consider this contrived code snippet:

class Fooer():
    def __init__(self, *args, **kwargs):
        # do things

    def foo(self) -> int:
        # do more things

def foo(fooer, *args, **kwargs) -> int:
    return x(*args, **kwargs).foo()

I want to hint that the fooer argument to foo() should be a subclass of Fooer. It's not an instance of Fooer, it's either Fooer itself or a subclass thereof. The best I could think of was

def foo(fooer: type, *args, **kwargs) -> int

which isn't specific enough.

How can I hint this better?

Upvotes: 1

Views: 77

Answers (2)

chepner
chepner

Reputation: 530823

From PEP-484 (The type of class objects), the solution is to use Type[C] to indicate subclasses of C, where C is a type var bounded by your base class.

F = TypeVar('F', bound=Fooer)

def foo(fooer: Type[F], *args,**kwargs) -> int:
    ...

(To be fair, I don't quite get the difference between using the TypeVar here, as indicated by PEP-484, versus using the class itself as in @e.s.'s answer.)

Upvotes: 3

e.s.
e.s.

Reputation: 1371

there a Type in typing

from typing import Type

class A(object):
    def __init__(self, thing):
        self.thing = thing

class B(A):
    pass

def make_it(a_class: Type[A]):
    return a_class(3)

make_it(B)  # type checks ok
make_it(str)  # type checks complaining

Upvotes: 2

Related Questions