New vs Old Style Python Classes in C Extensions?

Carl Banks pavlovevidence at
Sat Jan 27 13:51:19 CET 2007

On Jan 27, 6:11 am, Jeff Rush <j... at> wrote:
> While I have a reasonable understanding of the differences in new-style versus
> old-style classes, tonight while working a C extension module I realized I
> don't know how to indicate which style my C extension module should appear as.
> I'm following the Python docs for extended modules, but it doesn't say in
> there anyplace I can find which style I'm creating.  My clue that something
> was wrong is when this:
> from cextension import Context
> class MyContext(Context):
>      def __init__(self):
>          super(Context, self).__init__()
> repeatedly and reliably failed with a corrupted C data structure, while this:
> class MyContext(Context):
>      def __init__(self):
>          Context.__init__()
> worked without any problems.  As I understand it, the former uses new-style
> semantics while the latter uses old-style, and -thats- when I realized I have
> no idea which my C extension implemented.
> Any enlightenment?

Short answer:

It has nothing to do with old-style classes, and is probably just due 
to a mistake in your extension.

Longer answer:

C extention types have never implemented old-style classes.  Before 
Python 2.2, classes and types were different things.  All class 
instances were of the same type.  However, C extension objects were a 
different type, and weren't class instances at all.

Nowadays, new-style classes are types, but the converse isn't 
necessary true.  In particular, the typical way of defining old 
extension types didn't work as a new-style type.  So, as part of type-
class unification, they added some new fields (tp_members, tp_new, and 
so on) and new idioms to replace some of the old idioms, effectively 
creating "new-style types".

Unless you've adopted the new ways, your type isn't going to work as a 
class.  If you have adopted the new ways, then it's probably just a 
mistake in your code.

I suspect you have adopted the new ways, because I'd expect Python to 
raise TypeError when trying to subclass a function.  So you probably 
just have a bug.

Carl Banks

More information about the Python-list mailing list