NameVergessen
NameVergessen

Reputation: 643

Typehint for subclasses in Python

I am trying to do an orderly job with my type hints to have a code that is easier to add to.

I have made the following classes:

class Player(ABC)
    @abstractmethod
    def some_function():
        pass

class SomeSubclass(Player):
    def some_function():
        #some meaningfull code
        pass

p1: Type[Player] = SomeSubclass()

In the last line I get an expected type error by PyCharm:

Expected Type 'Type[Player]' got 'SomeSubclass' instead

Do I use the wrong Typehint or am I missing something else?

Upvotes: 5

Views: 4050

Answers (2)

Ofer Sadan
Ofer Sadan

Reputation: 11922

No need to use Type if the variable is expected to be an instance and not a class. Any of these should work:

p1: Player = SomeSubclass()

Or

p1: SomeSubclass = SomeSubclass()

Alternatively if you wanted p1 to be a class and not an instance:

p1: Type[Player] = SomeSubclass

Upvotes: 4

Samwise
Samwise

Reputation: 71424

You only need to use the Type[X] type declaration if you're typing a type (this is not a common situation -- an example might be if you had a factory function which takes a type, rather than an object instance, as its argument). To type an object, just use the type of the object:

p1: Player = SomeSubclass()

Note that even with no type hint, mypy is going to automatically infer that p1 is of type SomeSubclass and is therefore a Player. You only need to add the Player type hint if you want to explicitly downgrade p1 to a more general type so that you can assign a different subclass to it later.

Upvotes: 1

Related Questions