【问题标题】:How to call the whole function under 'with' statement in Python?如何在Python中的'with'语句下调用整个函数?
【发布时间】:2017-02-07 15:48:53
【问题描述】:

我有以下示例函数:

def Run(self):
    with self._resource() as r:
        # a lot of code uses |r|
        pass
    # end of 'with' statement
# end of function body

我不想因为with 语句中的额外缩进而丢失整个函数体的视觉空间。

我也不想在类范围之外调用_resource() - 它在某些方面破坏了封装,即这不是一个好方法:

with obj._resource() as r:
    obj.Run(r)

有什么漂亮的方法可以在不丢失视觉空间的情况下运行相同的代码?

【问题讨论】:

    标签: python python-2.7 with-statement syntactic-sugar


    【解决方案1】:

    如果你只处理这个函数,那就很简单了:

    class Foo(object):
        def Run(self):
            with self._resource() as r:
                return self._RunWithResource(r)
    
        def _RunWithResource(self, r):
            # ...
    

    如果您想重复该模式,装饰器可能会有所帮助。或多或少:

    from functools import wraps
    def with_resource(f):
        @wraps
        def wrapper(self, *a, **kw):
            with self._resource() as r:
                return f(self, r, *a, **kw)
        return wrapper
    
    class Foo(object):
        @with_resource
        def Run(self, r):
            # ...
    
    猜你喜欢
    • 2021-11-11
    • 1970-01-01
    • 1970-01-01
    • 2021-08-22
    • 2017-01-09
    • 1970-01-01
    • 2020-06-09
    • 1970-01-01
    • 2020-03-15
    相关资源
    最近更新 更多