Python3 context manager force shutdown

I need to create a context manager, which, when certain conditions are met, can be forced to exit it earlier.

More details:

The context manager must handle the check / lock / release of the resource. The __enter__context manager should check if the resource is locked. If so, I would like to __exit__call without executing code in context. Otherwise, the context manager acquires the resource, executes the context code, and clears the resource in __exit__.

It might look something like this:

class my_context_manager:
    def __enter__(self):
        if resource_locked():
            self.__exit__(None, ResourceLockedException(), None)
        else:
            acquire_resource()

    def __exit__(self, *exc_info):
        if not isinstance(exc_info[1], ResourceLockedException):
            release_resource()
        else:
            log.warn("Resource already in use.")

The code above does not actually work, since a call __exit__inside __enter__does not stop the execution of the code inside the context.

ResourceLockedException __enter__, __exit__ , . , , .

, , __exit__ . , ? ?

+5
1

, __exit__ . - raise . try-except :

from contextlib import contextmanager

@contextmanager
def log_exception():
    try:
        yield
    except ResourceLockedException as e:
        log.warn(e)

:

class my_context_manager:
    def __enter__(self):
        if True:
            raise ResourceLockedException("Resource already in use")
        acquire_resource()
    def __exit__(self):
        release_resource()

:

with log_exception(), my_context_manager():
    # do things when resource acquired. 

, try-except nest with if.

+1

Source: https://habr.com/ru/post/1663644/


All Articles