1

With the inspect and importlib library, we can get all functions in a .py file.

import importlib
import inspect

my_mod = importlib.import_module("mymod")
all_functions = inspect.getmembers(my_mod, inspect.isfunction)

However, the list all_functions includes not only functions defined in the module, but also functions imported to the module.

Is there a way to distinguish them?

1 Answers1

0

The key to the solution is function_name.__module__. Consider the following code:

import a as module_to_check

print(
    'checking module "{}"'
    .format(module_to_check.__name__))

for attr in dir(module_to_check):
    if callable(getattr(module_to_check, attr)):
        print(
            'function "{}" came from module "{}"'
            .format(
                getattr(module_to_check, attr).__name__,
                getattr(module_to_check, attr).__module__))

Output is:

checking module "a"
function "a_2" came from module "a"
function "b_2" came from module "b"

a.py is:

from b import b_1, b_2

a_1 = 1

def a_2():
    pass

b.py is:

b_1 = 1

def b_2():
    pass