如何在不传递参数或放置全局变量的情况下从其他作用域访问变量



我在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

你可以试试:

from mymodule import *

因为这应该从我的模块导入变量。

但它可能不会导入导入后创建的变量,因为它将 def 语句中的代码读取为调用时要执行的操作,它实际上并不创建变量。

最新更新