On Thu, 3 Sep 2020 at 18:06, haael <ha...@interia.pl> wrote: > 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`.
I'm not sure that would work in practice. If I pickle Local_here, then run a new instance of the program that loads in the pickle file, but has never even run f() in the new instance, then the class Local doesn't exist. So you can't unpikcle an instance of it, as you don't know how to create the class... Apologies if I'm misunderstanding your point here, but it feels like what you're proposing would only work if you pickled and unpickled the data in the *same* running instance of the program. Paul _______________________________________________ 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/5M6NM3TBAYUIWM4O52IXCK3UBFM2EBGR/ Code of Conduct: http://python.org/psf/codeofconduct/