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__ . , ? ?