【问题标题】:How to Wrap a Python 'With' Function and Reuse It Somewhere Else如何包装 Python 'With' 函数并在其他地方重用它
【发布时间】:2020-06-26 17:02:29
【问题描述】:

基本上我有一个 Python With 函数来进行站点登录。我所做的一切都需要属于With 函数,这样我才能继续进行站点连接。

如您所料,我有多个函数需要以 With 函数开头。它变得非常多余。但是如果我只是做一个普通的函数包装,我会失去站点连接。

我需要想办法正确包装With 函数。

【问题讨论】:

    标签: python with-statement


    【解决方案1】:

    我想出了答案。这是我要找的 Python 装饰器。

    def authenticate(f):
        @wraps(f)
        def wrapper(self, *args, **kwargs):
            self.site_url = kwargs.get('site_url', '')
            with self.sign_in(MY_TOKEN):
                # initiate server details here
                f(self, *args, **kwargs)
        return wrapper
    

    然后在我需要With的实际功能中,我这样做:

    @authenticate
    def my_func(site_url=''):
        # details of my_func
    

    注意site_url 是我的关键字参数。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-12-01
      • 2014-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-15
      • 1970-01-01
      相关资源
      最近更新 更多