Search for all defined functions in Python

Is there a way to find all the functions that were defined in python environment?

For example, if I had

def test: pass 

some_command_here will return test

+4
source share
5 answers

You can use the inspect module:

 import inspect import sys def test(): pass functions = [name for name, obj in inspect.getmembers(sys.modules[__name__], inspect.isfunction)] print functions 

prints:

 ['test'] 
+4
source

You can use globals() to capture everything defined in the global scope of the file, and inspect to filter objects of interest to you.

 [ f for f in globals().values() if inspect.isfunction(f) ] 
+4
source

Use globals() and types.FunctionType

 >>> from types import FunctionType >>> functions = [x for x in globals().values() if isinstance( x, FunctionType)] 

Demo:

 from types import FunctionType def func():pass print [x for x in globals().values() if isinstance(x, FunctionType)] #[<function func at 0xb74d795c>] #to return just name print [x for x in globals().keys() if isinstance(globals()[x], FunctionType)] #['func'] 
+2
source
 >>> def test(): ... pass ... >>> [k for k, v in globals().items() if callable(v)] ['test'] 
+1
source

First we create the test function we want to find.

 def test(): pass 

Then we will create the some_command_here function that you want.

 def some_command_here(): return filter(callable, globals().values()) 

Finally, we call the new function and convert the filter to tuple for viewing.

 tuple(some_command_here()) 

Note. . This searches for the current global namespace and returns all calls made (not just functions).


Example:

 >>> def test(): pass >>> def some_command_here(): return filter(callable, globals().values()) >>> tuple(some_command_here()) (<function test at 0x02F78660>, <class '_frozen_importlib.BuiltinImporter'>, <function some_command_here at 0x02FAFDF8>) >>> 
+1
source

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


All Articles