python - 如何在不传递参数或放置全局变量的情况下从其他 Scope 访问变量?
问题描述
我在 lambda 模块中有一个函数 lambda_handler ,包括其他模块并调用 helloWorld 函数。
在 helloWorld 函数中传递参数或将变量作为全局变量不是一种选择。是否可以从早期范围访问变量?
#--- lambda.py ---
import my_module
def lambda_handler(event,context):
my_module.helloWorld()
#--- my_module.py ---
def helloWorld():
local_variable = <something>.context
解决方案
使用inspect
模块获取调用框架的局部变量:
import inspect
def lambda_handler(event, context):
helloWorld()
def helloWorld():
calling_frame = inspect.currentframe().f_back
print(calling_frame.f_locals['event'])
print(calling_frame.f_locals['context'])
lambda_handler('an event', 'a context')
输出
an event
a context
推荐阅读
- javascript - 窗口“加载”addEventListener 不会触发
- python - 如何将目录中的每个项目与另一个目录中的每个项目进行比较?
- cryptography - 我什么时候应该使用 AutoSededRandomPool(而不是 NonblockingRng)?
- vue.js - 在 vuejs 中不使用导入使 JSON 从页面可见
- c++ - 无法添加门以防止我的代码第二次进入 if
- java - 为什么我的对象被 IntelliJ IDEA 的调试器无声地改变了?
- python - 了解 Python 装饰器
- python - 无法点击元素
- javascript - 有没有办法使用 webrtc 与其他用户共享文件路径?
- python-3.x - 如何以有效的方式计算前缀产品?