Published On: 1970-01-01|Last Updated: 1970-01-01|Categories: Uncategorized|
def save_type(self, obj, name=None):
"""add support for pickling a dynamic type
    >>> class A(object): pass
    >>> class B(object): pass
    >>> t = type('DynamicType', (A, B, ), {'a': 1, 'b': 2, })
    >>> t2 = loads(dumps(t))
    >>> t.__name__ == t2.__name__
    True
    >>> #t.__bases__ == t2.__bases__
    True
    >>> map(repr, t.__bases__) == map(repr, t2.__bases__)
    True
    >>> t.__dict__.keys() == t2.__dict__.keys()
    True
    """
try:
return _save_global(self, obj, name)
except PicklingError:
cls = type
__dict__ = obj.__dict__.copy()
if '__dict__' in __dict__: del __dict__['__dict__']
if '__weakref__' in __dict__: del __dict__['__weakref__']
args = (obj.__name__, obj.__bases__, __dict__, )
stuff = {}
self.write(MARK)
if self.bin:
self.save(cls)
for arg in args:
self.save(arg)
self.write(OBJ)
else:
for arg in args:
self.save(arg)
self.write(INST + cls.__module__ + '\n' + cls.__name__ + '\n')
self.memoize(obj)
self.save(stuff)
self.write(BUILD)
from pickle import *
from types import *
Pickler.dispatch[ClassType] = save_type
Pickler.dispatch[TypeType] = save_type
_save_global = Pickler.save_global
Pickler.save_global = save_type

関連