Getting a list of locally-defined functions in python
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
is here, since it's a function is the current module. You can move it to another module or exclude it manually, or define a lambda
instead (as @BartoszKP suggested).
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__)
Prints:
[('cube', <function cube at 0x027BAC70>), ('square', <function square at 0x0272BAB0>)]
l = []
for key, value in locals().items():
if callable(value) and value.__module__ == __name__:
l.append(key)
print l
So a file with the content:
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
Prints:
['square', 'cube']
Local scopes 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()
Prints out only:
['cube']
Using Python 3.9.7, When trying the most upvoted answer:
l = []
for key, value in locals().items():
if callable(value) and value.__module__ == __name__:
l.append(key)
print(l)
I got the following error: Traceback (most recent call last): File "C:\Users\Name\Path\filename.py", line X, in for key, value in locals().items(): RuntimeError: dictionary changed size during iteration
Because the answer: locals() prints this:
'test_01': <function test_01 at 0x00000285B0F2F5E0>
'test_02': <function test_02 at 0x00000285B0F2FA60>
I just check if we get the string: "function" in the dictionary.
I used the following code to achieve my needs. Hope maybe this can help.
l = []
copy_dict = dict(locals())
for key, value in copy_dict.items():
if "function" in str(value):
l.append(key)
print(l)