What is an instance and what isn't?

Dave Baum Dave.Baum at motorola.com
Thu May 24 14:45:53 EDT 2007


In article <HKedneXu0YpQMcjbnZ2dnUVZ_jCdnZ2d at bresnan.com>,
 "Gre7g Luterman" <hafeliel at yahoo.com> wrote:

> I suppose I was lulled into complacency by how Python makes so many things 
> look like classes, but I'm starting to realize that they're not, are they?
> 
> I'm writing a C program which handles Python objects in different ways based 
> on their type. I do a PyInstance_Check(PyObj) to determine if the PyObj is 
> an instance, but it is returning 0 on a lot of stuff that I thought would be 
> an instance. So I did the following simple test on three things that look 
> like instances:
> 
> Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] 
> on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> class a: pass
> ...
> >>> type(a())
> <type 'instance'>
> >>> type(Exception())
> <type 'exceptions.Exception'>
> >>> class b(dict): pass
> ...
> >>> type(b())
> <class '__main__.b'>
> 
> I was relieved that a() returns an instance, but I was surprised that 
> Exceptions aren't really instances at all. And what's the deal with derving 
> a class from a standard type like a dictionary? I thought for sure, that 
> would be an instance, but this shows it is a class?!?
> 


There are actually two kinds of classes in Python (as of 2.2): new-style 
classes and classic classes.  What you are calling an instance is an 
instance of a classic class.  Here is how a new-style class would look:

>>> class c(object): pass
... 
>>> type(c())
<class '__main__.c'>

Actually the new-style classes are a lot more consistent with the 
built-in types, and the type hierarchy makes more sense with them, so I 
would suggest in general migrating towards new-style classes for all of 
your own code.

More information about new-style classes can be found here: 
http://docs.python.org/ref/node33.html
http://www.python.org/doc/newstyle.html

> Can anyone explain the last one and/or give me a simple test I can do in C 
> to determine whether a Python object is "instance-like"?

With new-style classes, the type of an instance of that class is the 
class itself (type(x) == x.__class__).  In your above example, class b 
is a subclass of dict, which itself is a new-style class, making b a 
new-style class as well.  Thus type(b()) is b.

As for a check, it really depends on what you mean by "instance-like".  
Are dictionaries "instance-like"?  What about strings?  Integers?

Dave



More information about the Python-list mailing list