@@ -160,7 +160,11 @@ def ensurer(ensure_function):
160
160
function - for example checking if a laser is connected ahead of trying to set its power.
161
161
This way one ensurer can be written and used in multiple places easily.
162
162
163
- For example, an ensurer can be defined as a Piece's method (in the main body of the class)::
163
+ Note that **the method being decorated should raise an exception if the check fails!** This way
164
+ execution will stop if the condition is not met. This is not mandatory though - custom behaviour
165
+ is allowed.
166
+
167
+ For example, an ensurer can be defined as a Piece's method (in the main body of the class).::
164
168
165
169
@puzzlepiece.piece.ensurer
166
170
def _ensure_connected(self):
@@ -179,14 +183,20 @@ def power(self, value):
179
183
def wavelength(self, value):
180
184
self.laser.set_wavelength(value)
181
185
182
- It can also be called directly if preferred::
186
+ It can also be called directly if preferred, optionally with `capture_exception=True`
187
+ which will return True if the check passes, or False if the check raises an Exception::
183
188
189
+ # This should raise an Exception is the check fails
184
190
self._ensure_connected()
191
+
192
+ # This will not raise an Exception is the check fails
193
+ if self._ensure_connected(capture_exception=True):
194
+ print("laser is connected!")
185
195
"""
186
196
# Decorating a class method with ensure makes it a decorator.
187
197
# Here we create this decorator and return it.
188
198
@wraps (ensure_function )
189
- def ensure_decorator (self , main_function = None ):
199
+ def ensure_decorator (self , main_function = None , capture_exception = False ):
190
200
if main_function is not None :
191
201
# This means ensure_decorator was used as a decorator, and
192
202
# main_function is the function being decorated. We therefore
@@ -200,5 +210,12 @@ def wrapped_main(self, *args, **kwargs):
200
210
# If main_function is None, ensure_decorator has been called
201
211
# directly instead of being used as a decorator, so we
202
212
# just execute ensure_function
203
- ensure_function (self )
213
+ if capture_exception :
214
+ try :
215
+ ensure_function (self )
216
+ except :
217
+ return False
218
+ return True
219
+ else :
220
+ ensure_function (self )
204
221
return ensure_decorator
0 commit comments