cloudpipe / cloudpickle

Extended pickling support for Python objects
Other
1.64k stars 167 forks source link

Get the source code of a given method from a pickled class #456

Closed Afilnor closed 2 years ago

Afilnor commented 2 years ago

Given the following pickle (python3.8)

import cloudpickle

class A:
    def __init__(self, i: int):
        self.i = i

    def a_method(self, sentence: str) -> str:
        b: str = sentence * self.i
        return b

a = A(i=2)  

with open("mypickle", "wb") as f:
    cloudpickle.dump(a, f)

Would it be possible to retrieve the source code as a string of the a_method as : 'def a_method(self, sentence: str) -> str:\n b: str = sentence * self.i\n return b\n'

The class instance is pickled by value and I don't have a reference to the original class definition.

pierreglaser commented 2 years ago

Does the std-lib inspect.getsource fill your purpose? If not, why?

Afilnor commented 2 years ago

Yes I think that should do thanks!