@@ -60,7 +60,10 @@ def __init__(self, hub, layer):
60
60
self ._layer = layer
61
61
62
62
def __enter__ (self ):
63
- return self
63
+ scope = self ._layer [1 ]
64
+ if scope is None :
65
+ scope = Scope ()
66
+ return scope
64
67
65
68
def __exit__ (self , exc_type , exc_value , tb ):
66
69
assert self ._hub .pop_scope_unsafe () == self ._layer , "popped wrong scope"
@@ -205,13 +208,20 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
205
208
while len (scope ._breadcrumbs ) >= client .options ["max_breadcrumbs" ]:
206
209
scope ._breadcrumbs .popleft ()
207
210
208
- def push_scope (self ):
211
+ def push_scope (self , callback = None ):
209
212
"""Pushes a new layer on the scope stack. Returns a context manager
210
- that should be used to pop the scope again."""
213
+ that should be used to pop the scope again. Alternatively a callback
214
+ can be provided that is executed in the context of the scope.
215
+ """
211
216
client , scope = self ._stack [- 1 ]
212
217
new_layer = (client , copy .copy (scope ))
213
218
self ._stack .append (new_layer )
214
- return _ScopeManager (self , new_layer )
219
+
220
+ if callback is not None :
221
+ if client is not None :
222
+ callback (scope )
223
+ else :
224
+ return _ScopeManager (self , new_layer )
215
225
216
226
def pop_scope_unsafe (self ):
217
227
"""Pops a scope layer from the stack. Try to use the context manager
@@ -224,18 +234,28 @@ def configure_scope(self, callback=None):
224
234
"""Reconfigures the scope."""
225
235
client , scope = self ._stack [- 1 ]
226
236
if callback is not None :
227
- if client is not None and scope is not None :
237
+ if client is not None :
228
238
callback (scope )
229
239
return
230
240
231
241
@contextmanager
232
242
def inner ():
233
- if client is not None and scope is not None :
243
+ if client is not None :
234
244
yield scope
235
245
else :
236
246
yield Scope ()
237
247
238
248
return inner ()
239
249
250
+ def scope (self , callback = None ):
251
+ """Pushes a new scope and yields it for configuration.
252
+
253
+ The scope is dropped at the end of the with statement. Alternatively
254
+ a callback can be provided similar to `configure_scope`.
255
+ """
256
+ with self .push_scope ():
257
+ client , scope = self ._stack [- 1 ]
258
+ return self .configure_scope (callback )
259
+
240
260
241
261
GLOBAL_HUB = Hub ()
0 commit comments