Only objects of globally defined classes are picklable:
class Global:
pass
picklable = Global()
def f():
class Local:
pass
return Local
Local_here = f()
unpicklable = Local_here()
However, instances become picklable if we assign the local class to some
globally reachable identifier.
Local_here.__qualname__ = 'Local_here'
now_picklable = Local_here()
Why not make it a feature? Let's define module level global identifier,
for instance `__local_classes__`. It will be a weak dictionary of class
objects. Whenever a local class is created, a weak ref is made and
reflected in the new classes' qualname.
def f():
class Local:
pass
# weak ref is created with some unique id
return Local
Local_here = f()
print(Local_here.__qualname__) # '__local_classes__["uniqueidxxx"]'
assert Local_here is __local_classes__["uniqueidxxx"]
Likewise for local functions.
This would make many objects picklable, which also positively affects
modules that rely on `pickle`, like `multiprocessing`.
_______________________________________________
Python-ideas mailing list -- python-ideas@python.org
To unsubscribe send an email to python-ideas-le...@python.org
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at
https://mail.python.org/archives/list/python-ideas@python.org/message/B3NE6UAJP7K3YPJXI55HYDQQEBSH3BIK/
Code of Conduct: http://python.org/psf/codeofconduct/