@@ -252,6 +252,72 @@ first argument.
252
252
253
253
.. _resource-provider-wiring-closing :
254
254
255
+ Scoping Resources using specialized subclasses
256
+ ----------------------------------------------
257
+
258
+ You can use specialized subclasses of ``Resource `` provider to initialize and shutdown resources by type.
259
+ Allowing for example to only initialize a subgroup of resources.
260
+
261
+ .. code-block :: python
262
+
263
+ class ScopedResource (resources .Resource ):
264
+ pass
265
+
266
+ def init_service (name ) -> Service:
267
+ print (f " Init { name} " )
268
+ yield Service()
269
+ print (f " Shutdown { name} " )
270
+
271
+ class Container (containers .DeclarativeContainer ):
272
+
273
+ scoped = ScopedResource(
274
+ init_service,
275
+ " scoped" ,
276
+ )
277
+
278
+ generic = providers.Resource(
279
+ init_service,
280
+ " generic" ,
281
+ )
282
+
283
+
284
+ To initialize resources by type you can use ``init_resources(resource_type) `` and ``shutdown_resources(resource_type) ``
285
+ methods adding the resource type as an argument:
286
+
287
+ .. code-block :: python
288
+
289
+ def main ():
290
+ container = Container()
291
+ container.init_resources(ScopedResource)
292
+ # Generates:
293
+ # >>> Init scoped
294
+
295
+ container.shutdown_resources(ScopedResource)
296
+ # Generates:
297
+ # >>> Shutdown scoped
298
+
299
+
300
+ And to initialize all resources you can use ``init_resources() `` and ``shutdown_resources() `` without arguments:
301
+
302
+ .. code-block :: python
303
+
304
+ def main ():
305
+ container = Container()
306
+ container.init_resources()
307
+ # Generates:
308
+ # >>> Init scoped
309
+ # >>> Init generic
310
+
311
+ container.shutdown_resources()
312
+ # Generates:
313
+ # >>> Shutdown scoped
314
+ # >>> Shutdown generic
315
+
316
+
317
+ It works using the :ref: `traverse ` method to find all resources of the specified type, selecting all resources
318
+ which are instances of the specified type.
319
+
320
+
255
321
Resources, wiring, and per-function execution scope
256
322
---------------------------------------------------
257
323
0 commit comments