Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting a list of 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 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.

like image 469
beroe Avatar asked Aug 26 '13 19:08

beroe


People also ask

How do I list all functions in a Python 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.

Can you list functions in Python?

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.

How do you find the user defined function in Python?

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.

How do you display the contents of a function in Python?

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.


2 Answers

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)
like image 121
MarcM Avatar answered Oct 26 '22 17:10

MarcM


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).

like image 25
alecxe Avatar answered Oct 26 '22 18:10

alecxe