Is there a Magic Method for type() in python?

1.4k views Asked by At

I was wondering if there was a magic method in Python that supported the type() built-in function, that would allow you to set a custom value to be returned.

1

There are 1 answers

0
Martijn Pieters On BEST ANSWER

No, there is no such method. An instance's type is not something you can dynamically alter when querying for it, as that would be type-specific behaviour, but you suddenly cannot determine the type that is defining that behaviour!

You can assign a different class to instance.__class__, but then you'd materially alter the behaviour of that instance, and it is not the instance itself that then changes type when type() is applied to the instance.

Rather than using type(), use the isinstance() and issubclass() functions instead, and use abstract base types; it is the type object that is then responsible for claiming a specific class or instance as a subclass or instance of the given type, respectively. They can do this via the __issubclass__ and __isinstance__ hooks.