首页 > 解决方案 > 如何获取某个 .py 文件中定义的所有函数?

问题描述

使用 inspect 和 importlib 库,我们可以在 .py 文件中获取所有函数。

import importlib
import inspect

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

但是,该列表all_functions不仅包括模块中定义的函数,还包括导入模块的函数。

有没有办法区分它们?

标签: pythonmetaprogramming

解决方案


解决方案的关键是function_name.__module__。考虑以下代码:

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

输出是:

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

a.py是:

from b import b_1, b_2

a_1 = 1

def a_2():
    pass

b.py是:

b_1 = 1

def b_2():
    pass

推荐阅读