Determining if an object is a class?

C

Clay_Culver

I need to find out if an object is a class. Using new style classes
this is very easy:

class Test(object): pass

obj = Test
or
obj = Test()

if type(obj) == type:
# this is a class object..
else:
# this not a class object

But this fails for old style classes. For example:

class OldStyleObject: pass
<type 'classobj'>

But I have no way of comparing the return value to anything:Error, classobj not defined!

Since this is all duck typed, I have no idea what the class will be
passed in as, so I can't just compare the raw object. I have a
solution for this:

if str(type(Test)).find('classobj') != -1:
# this is a class object

Which is quite simply awful...does anyone know of a better way to do
this?
 
D

Dino Viehland

The first check is also off - it should if issubclass(type(Test), type): otherwise you miss the metaclass case:

class foo(type): pass

class Test(object):
__metaclass__ = foo

obj = Test
if type(obj) == type: 'class obj'
else: 'not a class'

just on the off-chance you run into a metaclass :)

-----Original Message-----
From: [email protected] [mailto:p[email protected]] On Behalf Of Clay Culver
Sent: Wednesday, July 12, 2006 2:07 PM
To: (e-mail address removed)
Subject: Re: Determining if an object is a class?

Ahh much better. Thanks.
 
P

placid

I need to find out if an object is a class. Using new style classes
this is very easy:

class Test(object): pass

obj = Test
or
obj = Test()

if type(obj) == type:
# this is a class object..
else:
# this not a class object

But this fails for old style classes. For example:

class OldStyleObject: pass

Why is there old and new classes? What are the differences?

--Cheers
 
M

Michael Spencer

Michele said:
inspect.isclass

M.S.
....which made me wonder what this canonical test is. The answer:

def isclass(object):
"""Return true if the object is a class.

Class objects provide these attributes:
__doc__ documentation string
__module__ name of module in which this class was defined"""
return isinstance(object, types.ClassType) or hasattr(object, '__bases__')

I wonder why the test isn't

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

Michael
 
C

Clay Culver

Dino said:
The first check is also off - it should if issubclass(type(Test), type): otherwise you miss the metaclass case:

class foo(type): pass

class Test(object):
__metaclass__ = foo

obj = Test
if type(obj) == type: 'class obj'
else: 'not a class'

just on the off-chance you run into a metaclass :)

Ah right...it's so easy to forget about metaclassing, despite how easy
Python makes it. Good catch, thanks.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,780
Messages
2,569,609
Members
45,253
Latest member
BlytheFant

Latest Threads

Top