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

后端 未结 2 466
清酒与你
清酒与你 2021-01-01 05:22

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 a

相关标签:
2条回答
  • 2021-01-01 05:31

    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.

    0 讨论(0)
  • 2021-01-01 05:45

    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

    0 讨论(0)
提交回复
热议问题