微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何通过上下文管理器和装饰器在特定上下文中定义全局函数

如何解决如何通过上下文管理器和装饰器在特定上下文中定义全局函数

我正在尝试使用上下文管理器和装饰器创建只能在特定上下文中访问的全局函数。到目前为止,我已经能够实现如下所示的内容(我删除了与问题无关的代码):

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 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?