This adds a new calling() method to CircuitBreaker. This method returns a context manager, enabling the circuit breaker to be used with a with statement. The block of code inside the with statement will be executed according to the rules implemented by the current state of the circuit breaker.
db_breaker = CircuitBreaker()
# Will trigger the circuit breaker
with db_breaker.calling():
# Do stuff here...
pass
Implementation Details
Initially, I attempted to make the CircuitBreaker itself a context manager, by implementing __enter__ and __exit__ in the class itself, but this required an amount of refactoring that I was not comfortable with. Therefore, I opted to implement this on top of the existing call method.
As for the naming of the new method, I took inspiration from PEP 0343, where the authors suggested using paste tense ("-ed") or progressive tense ("-ing"). Even though the new method itself isn't calling the with block itself, conceptually, it can be thought of doing so.
Summary
This adds a new
calling()
method toCircuitBreaker
. This method returns a context manager, enabling the circuit breaker to be used with awith
statement. The block of code inside thewith
statement will be executed according to the rules implemented by the current state of the circuit breaker.Fixes: https://github.com/danielfm/pybreaker/issues/85
Example usage:
Implementation Details
Initially, I attempted to make the
CircuitBreaker
itself a context manager, by implementing__enter__
and__exit__
in the class itself, but this required an amount of refactoring that I was not comfortable with. Therefore, I opted to implement this on top of the existingcall
method.As for the naming of the new method, I took inspiration from PEP 0343, where the authors suggested using paste tense ("-ed") or progressive tense ("-ing"). Even though the new method itself isn't calling the
with
block itself, conceptually, it can be thought of doing so.Test Plan
Added a test case that exercises the new API.