[Python-ideas] __intancehook__ special method

Yahya Abou 'Imran yahya-abou-imran at protonmail.com
Tue Dec 26 04:13:43 EST 2017


Hello everybody!

In a personnal project I feel the need (or the desire) to implement something like this:

assert isinstance(1, PositiveInteger)
assert not isinstance(-1, PositiveInteger)

So I began looking a lot in the abc module, and I end unp using an __instancehook__ special method wich is called by __instancechek__ in the corresponding metaclass, just like the __subclasshook__ special method called by __subclasscheck__.

The core idea is something like this:

class MyMeta(type):

    def __instancecheck__(cls, instance):

        return cls.__instancehook__(instance)

class PositiveInteger(metaclass=MyMeta):

    @classmethod

    def __instancehook__(cls, instance):

        return isinstance(instance, int) and instance > 0

Of course, the real implemention is more detailed...

What do you think about that ?
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20171226/37a8a14a/attachment.html>


More information about the Python-ideas mailing list