问题
To be short, suppose I have a string 'next',
next = "123rpq"
and I can apply a str method .isdigit() to 'next'. So my question is how to check the implementation of this method. Hence is there a thing like inspect.getsource(somefunction) to get the source code of a 'method'?
UPDATE: see comment about variable name 'next' below.
回答1:
For modules, classes, functions and a few other objects you can use inspect.getfile or inspect.getsourcefile. However, for builtin objects and methods this will result in a TypeError. As metioned by C0deH4cker, builtin objects and methods are implemented in C, so you will have to browse the C source code. isdigit is a method of the builtin string object, which is implemented in the file stringobject.c in the Objects directory of the Python source code. This isdigits method is implemented from line 3392 of this file. See also my answer here to a similar but more general question.
回答2:
The isdigit() method you are talking about is a builtin method of a builtin datatype. Meaning, the source of this method is written in C, not Python. If you really wish to see the source code of it, then I suggest you go to http://python.org and download the source code of Python.
回答3:
You can try printing method.__doc__ for the documentation on that particular method. If you are just curious, you could check your PYTHONPATH to see where your modules are imported from, and see if you find the .py file from that module
回答4:
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.
来源:https://stackoverflow.com/questions/11253955/how-to-check-source-code-of-a-python-method