Search code examples
pythonintrospection

why does python inspect.isclass think an instance is a class?


Given the following module:

class Dummy(dict):
    def __init__(self, data):
        for key, value in data.iteritems():
            self.__setattr__(key, value)

    def __getattr__(self, attr):
        return self.get(attr, None)
    __setattr__=dict.__setitem__
    __delattr__=dict.__delitem__


foo=Dummy({"one":1, "two":2})

why does foo show up in the output of inspect.getmembers(..., predicate=inspect.isclass)?

$ python2.5
Python 2.5.2 (r252:60911, Aug 28 2008, 13:13:37) 
[GCC 4.1.2 20071124 (Red Hat 4.1.2-42)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import junk
>>> import inspect
>>> inspect.getmembers(junk, predicate=inspect.isclass)
[('Dummy', <class 'junk.Dummy'>), ('foo', {'two': 2, 'one': 1})]
>>> inspect.isclass(junk.foo)
True

I expected that inspect would only return Dummy since that is the only class definition in the module. Apparently, though, junk.foo is a class in the eyes of the inspect module. Why is that?


Solution

  • Prior to Python v2.7, inspect.isclass naively assumed anything with a __bases__ attribute must be a class.

    Dummy's __getattr__ makes Dummy instances appear to have every attribute (with a value of None).

    Therefore, to inspect.isclass, foo appears to be a class.

    Note: __getattr__ should raiseAttributeError when asked for an attribute it does not know about. (This is very different than returning None.)