Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 840
Gilbert Allen Avatar asked Oct 27 '25 02:10

Gilbert Allen


1 Answers

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.

like image 84
Martijn Pieters Avatar answered Oct 28 '25 18:10

Martijn Pieters



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!