__instancecheck__ - overwrite shows no effect - what am I doing wrong?

本小妞迷上赌 提交于 2019-11-30 20:26:12

问题


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?


回答1:


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.




回答2:


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



来源:https://stackoverflow.com/questions/52168971/instancecheck-overwrite-shows-no-effect-what-am-i-doing-wrong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!