Collectives™ on Stack Overflow

Find centralized, trusted content and collaborate around the technologies you use most.

Learn more about Collectives

Teams

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Learn more about Teams

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)

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

In particular the lack of AttributeError which will cause truly stupendously horrible bugs. – Katriel Nov 2, 2010 at 20:51

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))
                Excellent point! I was looking at the v2.6 source. I edited my answer to indicate that __bases__ is no longer used in v2.7+.
– Jon-Eric
                Nov 2, 2010 at 21:14
        

Thanks for contributing an answer to Stack Overflow!

  • Please be sure to answer the question. Provide details and share your research!

But avoid

  • Asking for help, clarification, or responding to other answers.
  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.