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 the functions defined locally in the program ['square', 'cube']
, and not the ones imported.
They are included when I try dir()
but so are all the variables and other imported modules. I don't know what to put into dir
to refer to the locally executing file.
Method 1: Using the dir() Function: We have first to import the module in the Python shell, and then we have to write the module name in the dir() method, and it will return the list of all functions present in a particular Python module.
In Python, you can use a list function which creates a collection that can be manipulated for your analysis. This collection of data is called a list object. While all methods are functions in Python, not all functions are methods.
In Python, a user-defined function's declaration begins with the keyword def and followed by the function name. The function may take arguments(s) as input within the opening and closing parentheses, just after the function name followed by a colon.
Practical Data Science using Python We use the getsource() method of inspect module to get the source code of the function. Returns the text of the source code for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a single string.
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)
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).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With