PyFox
PyFox

Reputation: 373

User defined object as function specified parameter type in Python

I defined my class Player in Python3 and now I am trying to define a method in another class that would take an object type Player as a parameter, so a code would look like that:

def change_player_activity(self, player: Player):
    pass

But that gives me an error. I know that I could do a following operation:

if not isinstance(player,Player):
        raise TypeError

But I am just wondering, is there any built-in way to tell Python3 to accept only the objects of given class?

Upvotes: 1

Views: 609

Answers (1)

wizzwizz4
wizzwizz4

Reputation: 6426

Is there any built-in way to tell Python3 to accept on the objects of a given class?

No.

This doesn't exist, and wouldn't be useful anyway because Python relies on the principle of Duck Typing. If it looks like a Player, and quacks like a Player, treat it as a player. Otherwise, raise TypeError.

You should only be raising TypeError when you ask the object to do something that a Player should be able to do, and it can't do that. What if somebody wants to pass an instance of their own Player class into your function? It won't work then.


Back to your actual problem: You want to type-hint Player before Player is defined. The way to do this is to write "Player" instead of Player in the type hint:

def change_player_activity(self, player: "Player"):
    pass

In __future__ (pun intended), the Python developers plan to make it not try to look up type hints straight away because this sort of thing is a pain.

Upvotes: 2

Related Questions