首页 > 解决方案 > 如何在不传递参数或放置全局变量的情况下从其他 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    

标签: python

解决方案


使用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

推荐阅读