问题描述
我正在尝试使用上下文管理器和装饰器创建只能在特定上下文中访问的全局函数。到目前为止,我已经能够实现如下所示的内容(我删除了与问题无关的代码):
Mod.py
def canUseFooBar(func):
def wrapper():
global Foo
if "Foo" in globals():
raise ValueError("Error: The user already defined the function Foo")
else:
def Foo():
print("Global function Foo has been called")
# The rest of the functions would be protected in the same way in order to protect accidental overrides
global Section
@contextmanager
def Section():
global Bar
def Bar():
print("Global function Bar has been called")
yield None
del Bar
func()
del Foo
del Section
return wrapper
UserCode.py
import ModPackage.Mod as MOD
@canUseFooBar
def userFunction_01():
# The function can use Foo
# And Bar only inside a "Section"
MOD.Foo()
with MOD.Section():
MOD.Bar()
def userFunction_02():
# This function cannot use neither,Foo,Section() nor Bar()
# It would raise a ValueError
MOD.Foo()
with MOD.Section():
MOD.Bar()
这有点像我想要实现的,但是,我真正想做的是对用户来说看起来像这样的事情:>
UserCode.py
#Some import
@canUseFooBar
def userFunction_01():
Foo()
with Section():
Bar()
我可以在全局命名空间中使用一些函数,因为此功能不是设计用于大型项目,而是设计用于用户只编写一个函数的非常小的脚本 API。
此外,最终,用户甚至不必为装饰器和导入而烦恼,因为他会要求用户提供脚本的路径,而 api 将自动装饰函数并创建导入。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)