Identifying that a variable is a new-style class in Python?
Posted
by Dave Johansen
on Stack Overflow
See other posts from Stack Overflow
or by Dave Johansen
Published on 2010-04-16T16:33:33Z
Indexed on
2010/04/16
17:03 UTC
Read the original article
Hit count: 315
I'm using Python 2.x and I'm wondering if there's a way to tell if a variable is a new-style class? I know that if it's an old-style class that I can do the following to find out.
import types
class oldclass:
pass
def test():
o = oldclass()
if type(o) is types.InstanceType:
print 'Is old-style'
else:
print 'Is NOT old-style'
But I haven't been able to find anything that works for new-style classes. I found this question, but the proposed solutions don't seem to work as expected, because simple values as are identified as classes.
import inspect
def newclass(object):
pass
def test():
n = newclass()
if inspect.isclass(n):
print 'Is class'
else:
print 'Is NOT class'
if inspect.isclass(type(n)):
print 'Is class'
else:
print 'Is NOT class'
if inspect.isclass(type(1)):
print 'Is class'
else:
print 'Is NOT class'
if isinstance(n, object):
print 'Is class'
else:
print 'Is NOT class'
if isinstance(1, object):
print 'Is class'
else:
print 'Is NOT class'
So is there anyway to do something like this? Or is everything in Python just a class and there's no way to get around that?
© Stack Overflow or respective owner