5

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?

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.