globals - 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')
解决方案
因此,经过一段时间的来回折腾,我终于找到了解决问题的方法。
正如我所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"]
这有点“狡猾”,因为检查不适用于生产环境,但是可以工作并解决我的问题
推荐阅读
- python - 如何在 sklearn 中获取 tf 和 df 向量?
- python - Python 选择器库 - 如何在同一个套接字上发送两种方式?
- arrays - 将值添加到 VBA 对象的数组
- reactjs - 使用 reactjs 在模态中保持标签
- php - 将数据插入数据库的正确方法是什么?
- asp.net-core - .Net Framework 和 .Net Core 中的 AzureAD/OIDC 身份验证差异
- php - 如何检测用户是否更改了密码并撤销其他设备上的会话?
- django - Django 视图中的 FormData 为空或无
- python-3.x - OpenCV - 使用开放(非封闭)Canny 轮廓线作为遮罩的边界
- java - Spring Boot Rest:避免请求拒绝,消耗一切