Skip to content

Instantly share code, notes, and snippets.

@rossmacarthur
Created August 27, 2018 08:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rossmacarthur/179e2be24345173787c40a6f68ea658e to your computer and use it in GitHub Desktop.
Save rossmacarthur/179e2be24345173787c40a6f68ea658e to your computer and use it in GitHub Desktop.
Pickle nested classes in Python
import inspect
import pickle
def allow_picklable_inner_classes(cls):
for name in dir(cls):
inner = getattr(cls, name)
if not name.startswith('_') and inspect.isclass(inner):
new_name = '{}.{}'.format(cls.__name__, inner.__name__)
inner.__name__ = new_name
globals()[new_name] = inner
return cls
@allow_picklable_inner_classes
class Outer(object):
class Inner(object):
pass
obj_1 = Outer.Inner()
obj_2 = pickle.loads(pickle.dumps(obj_1))
assert type(obj_1) == type(obj_2)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment