The short answer is no, you cannot pickle methods but you can pickle functions (built-in and user-defined) accessible from the top level of a module (using def, not lambda).
The Python documentation states the types that can be pickled and unpickled are:
- None, True, and False;
- integers, floating-point numbers, complex numbers;
- strings, bytes, bytearrays;
- tuples, lists, sets, and dictionaries containing only picklable objects;
- functions (built-in and user-defined) accessible from the top level of a module (using def, not lambda);
- classes accessible from the top level of a module;
- instances of such classes whose __dict__ or the result of calling __getstate__() is picklable (see section Pickling Class Instances for details).
As per Wikipedia definition, serialization is:
the process of translating a data structure or object state into a format that can be stored (for example, in a file or memory data buffer) or transmitted (for example, over a computer network) and reconstructed later (possibly in a different computer environment).
The Pickle module simply wasn't built to serialize methods. The main purpose is to serialize state, the state of the attributes. The object is then instantiated when unpickling. As the method is part of the class definition, your code works fine but only with the later definition of the class. Thus etienne.name value end up being "etienne..".
In the context of an instance, saving the class definition also is usually inadequate and undesirable as instructions on how to use the serialized data may change in the future.
pickleactually saved was that there is an instance of a class namedPerson, defined in the module named__main__, containing an attributenamewith a certain value. When you unpickled that data, the current version of__main__.Personwas used, which isn't the same version of the class. Ifpickledidn't work that way, it would be impossible to fix bugs or add features to your code, as the pickled data would be stuck with the original definitions forever.