Listing locally defined functions in python

If I have a script like this:

import sys def square(x): return x*x def cube(x): return x**3 

How can I return a list of all functions defined locally in the program ['square', 'cube'] , and not imported.

They are included when trying dir() , but all variables and other imported modules. I do not know what to put in a dir to refer to a locally executable file.

+4
source share
3 answers
 l = [] for key, value in locals().items(): if callable(value) and value.__module__ == __name__: l.append(key) print l 

So, the file with the contents:

 from os.path import join def square(x): return x*x def cube(x): return x**3 l = [] for key, value in locals().items(): if callable(value) and value.__module__ == __name__: l.append(key) print l 

Print

 ['square', 'cube'] 

Local areas also work:

 def square(x): return x*x def encapsulated(): from os.path import join def cube(x): return x**3 l = [] for key, value in locals().items(): if callable(value) and value.__module__ == __name__: l.append(key) print l encapsulated() 

Only printed:

 ['cube'] 
+5
source

Use inspect module:

 def is_function_local(object): return isinstance(object, types.FunctionType) and object.__module__ == __name__ import sys print inspect.getmembers(sys.modules[__name__], predicate=is_function_local) 

Example:

 import inspect import types from os.path import join def square(x): return x*x def cube(x): return x**3 def is_local(object): return isinstance(object, types.FunctionType) and object.__module__ == __name__ import sys print [name for name, value in inspect.getmembers(sys.modules[__name__], predicate=is_local)] 

prints:

 ['cube', 'is_local', 'square'] 

See: no join function imported from os.path .

is_local here, as it is the current module. You can transfer it to another module or exclude it manually or define it instead of lambda (as suggested by @BartoszKP).

+7
source
 import sys import inspect from os.path import join def square(x): return x*x def cube(x): return x**3 print inspect.getmembers(sys.modules[__name__], \ predicate = lambda f: inspect.isfunction(f) and f.__module__ == __name__) 

Print

[('cube', <function cube at 0x027BAC70>), ('square', <function square at 0x0272BAB0>)]

+1
source

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


All Articles