How to check python method source code?

In short, suppose I have the string 'next' ,

 next = "123rpq" 

and I can apply the str .isdigit() method to 'next' . So my question is how to check the implementation of this method. Therefore, is there something like inspect.getsource(somefunction) to get the source code for the β€œmethod”?

UPDATE: see comment on variable name 'next' below.

+6
source share
4 answers

For modules, classes, functions, and several other objects, you can use inspect.getfile or inspect.getsourcefile . However, for built-in objects and methods, this will result in a TypeError . C0deH4cker believes that inline objects and methods are implemented in C, so you will need to look at the source code of C. isdigit is the inline string object method that is implemented in the stringobject.c file in the Objects directory in Python source code. This isdigits method isdigits implemented from line 3392 of this file. See Also my answer here to a similar, but more general question.

+7
source

The isdigit() method you are talking about is an inline method of an inline data type. Meaning, the source of this method is written in C, not Python. If you really want to see the source code, I suggest you go to http://python.org and download the Python source code.

+6
source

You can try printing method.__doc__ for documentation on this particular method. If you're just curious, you can check your PYTHONPATH to find out where your modules were imported from and see if a .py file was found from this module

0
source

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 .

0
source

Source: https://habr.com/ru/post/919286/


All Articles