[英]How to call the whole function under 'with' statement in Python?
I have the following sample function: 我有以下示例函数:
def Run(self):
with self._resource() as r:
# a lot of code uses |r|
pass
# end of 'with' statement
# end of function body
I don't want to lose the visual space of the whole function body because of additional indent inside with
statement. 我不想失去,因为额外的缩进内整体功能体的视觉空间with
声明。
Also I don't want to call the _resource()
outside the class scope - it breaks encapsulation in some ways, ie this is not a good way: 我也不想在类范围之外调用_resource()
-它以某些方式破坏了封装,即,这不是一个好方法:
with obj._resource() as r:
obj.Run(r)
Is there any pretty way to run the same code without losing visual space? 有什么漂亮的方法可以运行相同的代码而不损失可视空间?
If you have only this function to deal with, it's pretty simple: 如果只需要处理此功能,则非常简单:
class Foo(object):
def Run(self):
with self._resource() as r:
return self._RunWithResource(r)
def _RunWithResource(self, r):
# ...
If you want to repeat the pattern, a decorator might help. 如果要重复图案,装饰器可能会有所帮助。 More or less: 或多或少:
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):
# ...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.