[英]How to call the whole function under 'with' statement in Python?
我有以下示例函數:
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)
有什么漂亮的方法可以運行相同的代碼而不損失可視空間?
如果只需要處理此功能,則非常簡單:
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):
# ...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.