Created
August 27, 2018 08:36
-
-
Save rossmacarthur/179e2be24345173787c40a6f68ea658e to your computer and use it in GitHub Desktop.
Pickle nested classes in Python
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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