首页 > 解决方案 > Is there a way to access a variable from a calling function in python?

问题描述

I'm unsure if this is possible but I was wondering if there is a way to get a variable from an outer scope without passing it as an argument.

I've played around with global() and inspect but i'm having issues trying to get the attribute.

Here's what i'm trying to do:


class Example:
    @staticmethod
    def query(**kwargs):
        print(f.read())


with open(__file__) as f:
    Example.query(foo='bar')

标签: globals

解决方案


因此,经过一段时间的来回折腾,我终于找到了解决问题的方法。

正如我所Matthias建议的那样,我使用 global 来查找对象,我决定使用 inspect 自己添加它,如下所示:

分配

def __enter__(self):
    inspect.stack()[1][0].f_globals["_ExampleName"] = self

检索(固定)

    @staticmethod
    def _find_example():
        stack = inspect.stack()
        for stack_index in range(2, len(stack)):
            stack_globals = inspect.stack()[stack_index][0].f_globals
            if "_ExampleName" in stack_globals.keys():
                return stack_globals["_ExampleName"]

这有点“狡猾”,因为检查不适用于生产环境,但是可以工作并解决我的问题


推荐阅读