[Python-Dev] How to suppress instance dict? (original) (raw)

Joel de Guzman joel@boost-consulting.com
Tue, 1 Apr 2003 16:56:34 +0800


Dave Abrahams wrote:

I am generating extension types derived from a type which is derived from int 'int' by calling the metaclass; in order to prevent instances of the most-derived type from getting an instance dict I am putting an empty tuple in the class dict as 'slots'. The problem with this hack is that it disables pickling of these babies:

"a class that defines slots without defining getstate cannot be pickled"

Guido van Rossum wrote:

Yes. I was assuming you'd do this at the C level. To do what I suggested in Python, I think you'd have to write this:

class M(type): def new(cls, name, bases, dict): C = type.new(cls, name, bases, dict) del C.getstate return C

Hi,

Ok, I'm lost. Please be easy with me, I'm still learning the C API interfacing with Python :) Here's what I have so far. Emulating the desired behavior in Python, I can do:

class EnumMeta(type):
    def __new__(cls, name, bases, dict):
        C = type.__new__(cls, name, bases, dict)
        del C.__getstate__
        return C

class Enum(int):
    __metaclass__ = EnumMeta
    __slots__ = ()


x = Enum(1964)
print x

import pickle
print "SAVING"
out_x = pickle.dumps(x)

print "LOADING"
xl = pickle.loads(out_x)
print xl

I'm trying to rewrite this in C/C++ with the intent to patch Boost.Python to allow pickling on enums. I took on this task to learn more about the low level details of Python C interfacing.
So far, I have implemented EnumMeta in C that does not override anything yet and installed that as the metaclass of Enum.

I was wondering... Is there some C code somewhere that I can see that implements some sort of meta-stuff? I read PEP253 and 253 and "Unifying Types and Classes in Python 2.2". The examples there (specifically the class autoprop) is written in Python. I tried searching for examples in C from the current CVS snapsot of 2.3 but I failed in doing so. I'm sure it's there, but I don't know where to find.

To be specific, I'm lost in trying to implement tp_new of PyTypeObject. How do I call the default tp_new for metaclasses?

TIA,

Joel de Guzman joel at boost-consulting.com http://www.boost-consulting.com http://spirit.sf.net