@@ -60,7 +60,10 @@ def __init__(self, hub, layer):
6060 self ._layer = layer
6161
6262 def __enter__ (self ):
63- return self
63+ scope = self ._layer [1 ]
64+ if scope is None :
65+ scope = Scope ()
66+ return scope
6467
6568 def __exit__ (self , exc_type , exc_value , tb ):
6669 assert self ._hub .pop_scope_unsafe () == self ._layer , "popped wrong scope"
@@ -205,13 +208,20 @@ def add_breadcrumb(self, crumb=None, hint=None, **kwargs):
205208 while len (scope ._breadcrumbs ) >= client .options ["max_breadcrumbs" ]:
206209 scope ._breadcrumbs .popleft ()
207210
208- def push_scope (self ):
211+ def push_scope (self , callback = None ):
209212 """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+ """
211216 client , scope = self ._stack [- 1 ]
212217 new_layer = (client , copy .copy (scope ))
213218 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 )
215225
216226 def pop_scope_unsafe (self ):
217227 """Pops a scope layer from the stack. Try to use the context manager
@@ -224,18 +234,28 @@ def configure_scope(self, callback=None):
224234 """Reconfigures the scope."""
225235 client , scope = self ._stack [- 1 ]
226236 if callback is not None :
227- if client is not None and scope is not None :
237+ if client is not None :
228238 callback (scope )
229239 return
230240
231241 @contextmanager
232242 def inner ():
233- if client is not None and scope is not None :
243+ if client is not None :
234244 yield scope
235245 else :
236246 yield Scope ()
237247
238248 return inner ()
239249
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+
240260
241261GLOBAL_HUB = Hub ()
0 commit comments