| | 1 | from sage.misc.cachefunc import cached_function |
| | 2 | |
| | 3 | class bar: |
| | 4 | pass |
| | 5 | |
| | 6 | def metaclass(name, bases): |
| | 7 | """ |
| | 8 | Creates a new class in this metaclass |
| | 9 | |
| | 10 | INPUT:: |
| | 11 | - name: a string |
| | 12 | - bases: a tuple of classes |
| | 13 | |
| | 14 | EXAMPLES:: |
| | 15 | |
| | 16 | sage: from sage.misc.test_class_pickling import metaclass, bar |
| | 17 | sage: c = metaclass("foo2", (object, bar,)) |
| | 18 | constructing class |
| | 19 | sage: c |
| | 20 | <class 'sage.misc.test_class_pickling.foo2'> |
| | 21 | sage: type(c) |
| | 22 | <class 'sage.misc.test_class_pickling.Metaclass'> |
| | 23 | sage: c.__bases__ |
| | 24 | (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>) |
| | 25 | |
| | 26 | """ |
| | 27 | print "constructing class" |
| | 28 | result = Metaclass(name, bases, dict()) |
| | 29 | result.reduce_args = (name, bases) |
| | 30 | return result |
| | 31 | |
| | 32 | class Metaclass(type): |
| | 33 | """ |
| | 34 | This metaclass illustrates the customization of how a class is pickled. |
| | 35 | It requires a slightly patched version of cPickle. |
| | 36 | |
| | 37 | See: |
| | 38 | - http://docs.python.org/library/copy_reg.html#module-copy_reg |
| | 39 | - http://groups.google.com/group/comp.lang.python/browse_thread/thread/66c282afc04aa39c/ |
| | 40 | - http://groups.google.com/group/sage-devel/browse_thread/thread/583048dc7d373d6a/ |
| | 41 | |
| | 42 | EXAMPLES:: |
| | 43 | |
| | 44 | sage: from sage.misc.test_class_pickling import metaclass, bar |
| | 45 | sage: c = metaclass("foo", (object, bar,)) |
| | 46 | constructing class |
| | 47 | sage: import cPickle |
| | 48 | sage: s = cPickle.dumps(c) |
| | 49 | reducing a class |
| | 50 | sage: c2 = cPickle.loads(s) |
| | 51 | constructing class |
| | 52 | sage: c = c2 = 1 |
| | 53 | |
| | 54 | """ |
| | 55 | def __reduce__(self): |
| | 56 | """ |
| | 57 | Implements the pickle protocol for classes in this metaclass |
| | 58 | (not for the instances of this class!!!) |
| | 59 | |
| | 60 | EXAMPLES:: |
| | 61 | |
| | 62 | sage: from sage.misc.test_class_pickling import metaclass, bar |
| | 63 | sage: c = metaclass("foo3", (object, bar,)) |
| | 64 | constructing class |
| | 65 | sage: c.__class__.__reduce__(c) |
| | 66 | reducing a class |
| | 67 | (<function metaclass at ...>, ('foo3', (<type 'object'>, <class sage.misc.test_class_pickling.bar at ...>))) |
| | 68 | """ |
| | 69 | print "reducing a class" |
| | 70 | return (metaclass, self.reduce_args) |
| | 71 | |
| | 72 | |
| | 73 | import copy_reg |
| | 74 | copy_reg.pickle(Metaclass, Metaclass.__reduce__) |