<div dir="ltr"><div><div>>>> import pickle</div><div>>>> pickle.dumps(pickle.dumps)</div><div>'cpickle\ndumps\np0\n.'</div><div>>>> pickle.dumps(pickle)</div><div>Traceback (most recent call last):</div>
<div> File "<stdin>", line 1, in <module></div><div> File "C:\Runtimes\Python\lib\pickle.py", line 1374, in dumps</div><div> Pickler(file, protocol).dump(obj)</div><div> File "C:\Runtimes\Python\lib\pickle.py", line 224, in dump</div>
<div> self.save(obj)</div><div> File "C:\Runtimes\Python\lib\pickle.py", line 306, in save</div><div> rv = reduce(self.proto)</div><div> File "C:\Runtimes\Python\lib\copy_reg.py", line 70, in _reduce_ex</div>
<div> raise TypeError, "can't pickle %s objects" % base.__name__</div><div>TypeError: can't pickle module objects</div></div><div><br></div><div style>I know that you can't, but why not? You can pickle class objects and function objects in modules, and their static path is stored so that when you unpickle it, the correct module is imported and the function is retrieved from that module. It seems odd an inconsistent that you can't pickle the module object itself; can't it just store itself as a name, and have loads() import it and return the resultant module object?</div>
<div style><br></div><div style>This isn't entirely of academic interest; I'm working with some code which is meant to pickle/unpickle arbitrary things, and occasionally it blows up when i accidentally pass in a module. It's always possible to work around the TypeErrors by just changing the stuff I pass in for serializing from the module to the exact function/class i want, but it seems like needless pain.</div>
<div style><br></div><div style>Is there any good reason we don't let people pickle module objects using the same technique that we use to pickle classes and top-level functions?</div><div style><br></div><div style>
-Haoyi</div>
<div style><br></div><div style>-Haoyi</div></div>