To be short, suppose I have a string \'next\'
,
next = \"123rpq\"
and I can apply a str
method .isdigit()
While I'd generally agree that inspect
is a good answer, it falls flat when your class (and thus the class method) was defined in the interpreter.
If you use dill.source.getsource
from dill, you can get the source of functions and lambdas, even if they are defined interactively.
It also can get the code for from bound or unbound class methods and functions defined in curries... however, you might not be able to compile that code without the enclosing object's 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 may not have to resort to using your favorite editor to open the file with the source code in it (as suggested in other answers). There is a new package called cinspect that purports to be able to view source for builtins
.