在上下文管理器外部动态定义变量名称

问题描述 投票:0回答:1

我的设置是这样的

# main.py
class A:
    def __init__(self, name) -> None:
        self.name = name

    def __enter__(self):
        globals()[self.name] = self
        return self

    def __exit__(self, exec_type, exec_value, traceback) -> bool:
        return False

with A('foo'): pass
print(foo)

尽管 Pylance 对我尖叫,但它有效,我能够看到

foo
的存在。但如果我像这样分割代码

# ./src/module_name/fileA.py
class A:
    def __init__(self, name: str) -> None:
        self.name: str = name

    def __enter__(self):
        globals()[self.name] = self
        return self

    def __exit__(self, exec_type, exec_value, traceback) -> bool | None:
        return None

# ./tests/test_fileA.py
from module_name.fileA import A

with A('foo'): pass
print(foo)

它给出了错误

NameError: name 'foo' is not defined
我能做些什么 ? 我不想要像
with A('foo') as foo: pass

这样的语法

我正在 Ubuntu 20.04 上使用 Python3.11,试图制作我的第一个 python 包。 如果可能的话,请建议一种Python式的方法来做到这一点

python python-3.x contextmanager pylance
1个回答
0
投票

也许它没有回答你的问题,但在我看来,这根本不干净,应该避免。出于同样的目的,您可以使用 Python 的

dictionary

© www.soinside.com 2019 - 2024. All rights reserved.