new-style class instance check

R

Richard Gruet

Hi all,

How to determine that an object o is for sure an instance of a new-style
class, without knowing of which specific class ?
That is, if I define a function:

def isNewStyleClassInstance(o):
pass ## to be completed

... I want to pass the following test:

def C: pass
def CNew(object): pass

assert not isNewStyleClassInstance(C()) # InstanceType
assert isNewStyleClassInstance(CNew())
assert not isNewStyleClassInstance(1) # instance of type int
# and naturally for all other types of o the function should return False.

Richard
 
A

Aahz

How to determine that an object o is for sure an instance of a new-style
class, without knowing of which specific class ?
That is, if I define a function:

def isNewStyleClassInstance(o):
pass ## to be completed

.. I want to pass the following test:

def C: pass
def CNew(object): pass

assert not isNewStyleClassInstance(C()) # InstanceType
assert isNewStyleClassInstance(CNew())
assert not isNewStyleClassInstance(1) # instance of type int
# and naturally for all other types of o the function should return False.

class UserClass(object): pass

class CNew(UserClass): pass

You can automate this within a module by setting __metaclass__.
 
J

John Roth

Richard Gruet said:
Hi all,

How to determine that an object o is for sure an instance of a new-style
class, without knowing of which specific class ?
That is, if I define a function:

def isNewStyleClassInstance(o):
pass ## to be completed

.. I want to pass the following test:

def C: pass
def CNew(object): pass

assert not isNewStyleClassInstance(C()) # InstanceType
assert isNewStyleClassInstance(CNew())
assert not isNewStyleClassInstance(1) # instance of type int
# and naturally for all other types of o the function should return False.

The following untested code should work:

import types

def isNewStyleClass(obj):
if type(obj) is types.InstanceType:
if hasattr(obj.__class__, "__mro__"):
return True
return False



John Roth
 

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,774
Messages
2,569,598
Members
45,149
Latest member
Vinay Kumar Nevatia0
Top