Although I usually agree that inspect
is a good answer, it crashes when your class (and therefore the class method) was defined in the interpreter.
If you use dill.source.getsource
from dill
, you can get the source of functions and lambda, even if they are defined interactively. It can also get code for related or unrelated methods and class functions defined in curry ... however, you cannot compile this code without the attached object code.
>>> from dill.source import getsource >>> >>> def add(x,y): ... return x+y ... >>> squared = lambda x:x**2 >>> >>> print getsource(add) def add(x,y): return x+y >>> print getsource(squared) squared = lambda x:x**2 >>> >>> class Foo(object): ... def bar(self, x): ... return x*x+x ... >>> f = Foo() >>> >>> print getsource(f.bar) def bar(self, x): return x*x+x >>>
For builtin
functions or methods, dill.source
will not work ... HOWEVER ...
You still donβt have to resort to using your favorite editor to open the source file (as suggested in other answers). There is a new cinspect
package that is designed to view the source for builtins
.
source share