4848import abc
4949
5050from dimod .core .sampler import Sampler
51+ from dimod .core .scoped import Scoped
5152
5253__all__ = ['Composite' , 'ComposedSampler' ]
5354
5455
55- class Composite (abc . ABC ):
56+ class Composite (Scoped ):
5657 """Abstract base class for dimod composites.
5758
5859 Provides the :attr:`Composite.child` mixin property and defines the :attr:`Composite.children`
5960 abstract property to be implemented. These define the supported samplers for the composed sampler.
6061
62+ :class:`.Composite` implements the :class:`~dimod.core.scoped.Scoped` interface, and
63+ provides :meth:`.close` method that closes all child samplers or composites.
64+
65+ .. versionchanged:: 0.12.19
66+ Implemented the :class:`~dimod.core.scoped.Scoped` interface. Now all
67+ composites support context manager protocol and release scope-based
68+ resources of sub-samplers/composites by default.
6169 """
70+
6271 @abc .abstractproperty
6372 def children (self ):
6473 """list[ :obj:`.Sampler`]: List of child samplers that that are used by
@@ -74,6 +83,29 @@ def child(self):
7483 except IndexError :
7584 raise RuntimeError ("A Composite must have at least one child Sampler" )
7685
86+ def close (self ):
87+ """Release any scope-bound resources of child samplers or composites.
88+
89+ .. note::
90+ If a :class:`.Composite` subclass doesn't allocate resources that have
91+ to be explicitly released, there's no need to override the default
92+ :meth:`~.Composite.close` implementation.
93+
94+ However, if you do implement :meth:`~.Composite.close` on a subclass,
95+ make sure to either call ``super().close()``, or to explicitly close
96+ all child samplers/composites.
97+
98+ .. versionadded:: 0.12.19
99+ :class:`.Composite` now implements the :class:`~dimod.core.scoped.Scoped`
100+ interface. The default :meth:`~.Composite.close` method recursively closes
101+ composite's children.
102+ """
103+
104+ for child in self .children :
105+ if hasattr (child , 'close' ) and callable (child .close ):
106+ child .close ()
107+ super ().close ()
108+
77109
78110class ComposedSampler (Sampler , Composite ):
79111 """Abstract base class for dimod composed samplers.
0 commit comments