views:

2070

answers:

3

I was wondering how to check whether a variable is a class (not an instance!) or not.

I've tried to use the function isinstance(object, class_or_type_or_tuple) to do this, but I don't know what type would a class will have.

For example, in the following code

class Foo: pass  
isinstance(Foo, **???**) # i want to make this return True.

I tried to substitute "class" with ???, but I realized that class is a keyword in python.

Any help? Thanks.

+3  A: 
>>> class X(object):
...     pass
... 
>>> type(X)
<type 'type'>
>>> isinstance(X,type)
True
S.Lott
Hm... Nice answer, but when i do type(Foo) on my Foo class, it says <type 'classobj'> instead of <type 'type'>. I assume that the diference comes from the fact that X is inheriting from the object, but Foo isn't. Is there any other difference arising from this? Thanks.
jeeyoungk
@jeeyoungk Yes, google new-style and old-style classes.
Benjamin Peterson
It doesn't work for old-style classes: `'class Old:pass' 'isinstance(Old, type) == False'`, but `inspect.isclass(Old) == True`.
J.F. Sebastian
@jeeyoungk: You're not "assuming the difference comes from...", you're actually reading that in the code. A subclass of object ("new style") has the desired properties, just what you see here.
S.Lott
Here's the hint -- since this works for new-style classes, don't use old-style classes. There's no point to using old-style classes.
S.Lott
+14  A: 

Even better: use the inspect module.

>>> import inspect
>>> class X(object):
...     pass
... 
>>> inspect.isclass(X)
True
Benjamin Peterson
+1  A: 

class Foo: is called old style class and class X(object): is called new style class.

Check this http://stackoverflow.com/questions/54867/old-style-and-new-style-classes-in-python . New style is recommended. Read about "unifying types and classes"

JV