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 ?