[Python-ideas] __intancehook__ special method

Paul Moore p.f.moore at gmail.com
Tue Dec 26 06:14:22 EST 2017

On 26 December 2017 at 09:13, Yahya Abou 'Imran via Python-ideas
<python-ideas at python.org> wrote:
> 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)

To me, this seems like an over-use of classes for something they are
not really appropriate for (in Python, at least). In my experience,
it's people coming from other languages that are more strongly class
based, such as Java, that prefer this type of construct.

In Python, I'd write this as

    assert isinstance(1, int) and 1 > 0
    assert not isinstance(-1, int) or -1 < 0
    # or maybe you meant isinstance(-1, int) and -1 < 0 for the second one...?

That reads far more naturally to me in Python.

> 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__.
> What do you think about that ?

I don't think it's needed - it feels to me like a solution to a
problem that Python doesn't have in practice. (Of course, there may be
more complex or specialised cases where it would be useful, but as
you've demonstrated, you can write the implementation yourself for the
rare cases it might be needed, so that may well be sufficient).

Thanks for the idea - it's interesting to see how other people
approach problems like this even if it turns out not to be something
worth adding.


More information about the Python-ideas mailing list