7

I'm trying to make my class appear as a different object to circumvent lazy type checking in a package I'm using. More specifically, I'm trying to make my object appear as an instance of another object (tuple in my case) when in reality it is not even a derivation of that.

In order to achieve this, I plan to overwrite the __isinstance__ method which, according to the docs, should do exactly what I desire. However, it appears that I didn't understand how do to do that exactly, because my attempts have been unsuccessful.

Here's an SSCCE that should make isinstance return False in all cases but doesn't.

class FalseInstance(type):
    def __instancecheck__(self, instance):
        return False

class Foo(metaclass=FalseInstance):
    pass

g = Foo()
isinstance(g, Foo)
> True

What am I doing wrong?

Nearoo
  • 4,454
  • 3
  • 28
  • 39
  • What does the your non-tuple class look like? And does it implement all tuple methods that your package requires? The only real solution I can think of to your problem is subclass tuple, but override all its methods. – Dunes Sep 04 '18 at 16:32
  • @Dunes Thanks, I adjusted the question. I now also understand why the code I provided doesn't work. However, if I now flip the example and change it so that `__isinstance__` always returns _True_, it still doesn't work the way I'd expect it to: `isinstance(g, int)` still returns `False`. What is the problem here? – Nearoo Sep 04 '18 at 18:48
  • @Dunes To your second question - `tuples` are immutable and thus a little cumbersome to use, right? I don't know yet what aspects of a tuple are required for the package to work, but I thought I'd add them whenever exceptions are thrown... – Nearoo Sep 04 '18 at 18:50

2 Answers2

10

Aside from the issues with __metaclass__ and the fast-path for an exact type match, __instancecheck__ works in the opposite direction from what you're trying to do. A class's __instancecheck__ checks whether other objects are considered virtual instances of that class, not whether instances of that class are considered virtual instances of other classes.

If you want your objects to lie about their type in isinstance checks (you really shouldn't), then the way to do that is to lie about __class__, not implement __instancecheck__.

class BadIdea(object):
    @property
    def __class__(self):
        return tuple

print(isinstance(BadIdea(), tuple)) # prints True

Incidentally, if you want to get the actual type of an object, use type rather than checking __class__ or isinstance.

user2357112
  • 260,549
  • 28
  • 431
  • 505
  • Eeeek. This is indeed horrible. I wonder if it is an implementation detail that `isinstance` is fooled by this. – jsbueno Sep 04 '18 at 22:53
  • 1
    @jsbueno: I'm not sure. The standard library relies on it, notably in [unittest.mock](https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.__class__), but the docs for `isinstance` and `__class__` don't mention it. The [C API docs](https://docs.python.org/3/c-api/object.html#c.PyObject_IsInstance) mention it, but the C API is an implementation detail. – user2357112 Sep 04 '18 at 22:58
  • This goes directly against the PEP description, so perhaps a bug. But yes, a fast path checks for direct types first before `__instancecheck__` is called. – Martijn Pieters Mar 03 '19 at 15:00
  • 1
    See [this bug report](https://bugs.python.org/issue35083), there currently doesn't appear to be a consensus on whether this is a bug or documentation problem. – Martijn Pieters Mar 03 '19 at 15:06
7

If you add a print inside FalseInstance.__instancecheck__ you will see that it is not even invoked. However, if you call isinstance('str', Foo) then you'll see that FalseInstance.__instancecheck__ does get invoked.

This is due to an optimization in isinstance's implementation that immediately returns True if type(obj) == given_class:

int
PyObject_IsInstance(PyObject *inst, PyObject *cls)
{
    _Py_IDENTIFIER(__instancecheck__);
    PyObject *checker;

    /* Quick test for an exact match */
    if (Py_TYPE(inst) == (PyTypeObject *)cls)
        return 1;
    .
    .
    .
}

From Python's source code

DeepSpace
  • 78,697
  • 11
  • 109
  • 154
  • Really? What's the point of even providing __isinstance__ if not to change exactly this behaviour? – Nearoo Sep 04 '18 at 15:14
  • it looks like in python 2.7 it did work... : https://stackoverflow.com/a/13135792/8179099 – Moshe Slavin Sep 04 '18 at 15:16
  • 5
    @Nearoo: `__instancecheck__` is primarily intended to make more `isinstance` checks pass, not less. Also, there's no `__isinstance__`. – user2357112 Sep 04 '18 at 16:22
  • However, if I now flip the example and change it so that `__isinstance__` always returns _True_, it still doesn't work the way I'd expect it to: `isinstance(g, int)` now returns `False`. What is the problem here? – Nearoo Sep 04 '18 at 18:51
  • 1
    @Nearoo: *There is no `__isinstance__`.* There is only `__instancecheck__`, which works in the opposite direction from what you're trying to do. – user2357112 Sep 04 '18 at 19:26
  • Sorry, I meant `__instancecheck__`. But you're right, I got it the wrong way around. This clears it up, thanks a lot!! – Nearoo Sep 04 '18 at 20:01