python - 如何获取某个 .py 文件中定义的所有函数?
问题描述
使用 inspect 和 importlib 库,我们可以在 .py 文件中获取所有函数。
import importlib
import inspect
my_mod = importlib.import_module("mymod")
all_functions = inspect.getmembers(my_mod, inspect.isfunction)
但是,该列表all_functions
不仅包括模块中定义的函数,还包括导入模块的函数。
有没有办法区分它们?
解决方案
解决方案的关键是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
推荐阅读
- security - Docker 中的安全配置文件(docker build --security-opt)
- javascript - 为什么 Javascript 函数只有在 php 登录会话处于活动状态时才有效,但在注销时停止工作?
- spring - spring boot oauth2 - 使用基本身份验证时无法获取访问令牌
- python - VSCode:所选环境中没有可用的 Pip 安装程序
- python - Any easier way to assign values of a DataFrame row to corresponding variables in a custom object?
- windows - 为什么加载的 PE 二进制文件需要 IAT?
- javascript - Split interface into base and extras automatically
- amazon-web-services - Creating a Subdomain for an SFTP site on AWS
- django-rest-framework - Django Rest Framework - HyperlinkedRelatedField for abstract base class
- javascript - Trigger checkbox change event with plain javascript (NOT jQuery)