简体   繁体   中英

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.

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:

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):
        # ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM