开发者

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

开发者 https://www.devze.com 2023-01-23 09:09 出处:网络
Given the following module: class Dummy(dict): def __init__(self, data): for key, value in data.iteritems():

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 2开发者_如何学JAVA008, 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?


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.)


First if all great answer Jon-Eric i just wanted to add some stuff:

if you do in ipython (what a great tool):

%psource inspect.isclass

you will get:

return isinstance(object, types.ClassType) or hasattr(object, '__bases__')

which what Jon-Eric said.

but i guess that you use python < 2.6 and this bug was already fixed, this is the code of inspect.isclass() in python2.7:

return isinstance(object, (type, types.ClassType))
0

精彩评论

暂无评论...
验证码 换一张
取 消