Package: depocs
Scopedis a mixin class that creates a thread-local stack for each of its
subclasses. Instances of the subclass can be pushed and popped on this stack,
and the instance at the top of the stack is always available as a property of
the class.Scopedclasses are typically used to make parameters implicitly
available within a (dynamic) scope, without having to pass them around as
function arguments.Scopedhelps you do this in a safe and convenient way,
and provides very informative error messages when you do something wrong.ExamplesAScopedclass can be used to pass around contextual data:classSession(Scoped):def__init__(self,user):self.user=userdefprint_current_user():print(Session.current.user)withSession(some_guy):print_current_user()It can also be used to provide dependencies:classClock(Scoped):def__init__(self,now=None):self._now=nowdefnow(self):returnself._nowordatetime.now()Clock.default=Clock()defprint_time()print(Clock.current.now())print_time()# Prints the real timedeftest_print_fake_time(self):withClock(datetime(2000,1,1)):print_time()# Prints a fake timeOpening and ClosingScopedobjects are best used as context managers (i.e. using thewithstatement), but for situations where this isn’t possible, you can also open
and close them “manually”:classTransaction(Scoped):...transaction=Transaction().open()try:...finally:transaction.close()Obviously, you will need to do whatever is necessary to ensure that every
call toopenis matched by a call toclose.OptionsThe behavior ofScopedsubclasses can be customized by declaring
options in a nested class namedScopedOptions. Except where noted,
options are automatically inherited by subclasses that do not override
them:classThingy(Scoped):classScopedOptions:# If True, instances will share the stack of their parent class.# If False, this class will have its own stack independent of any# ancestors. The default is to inherit the stack, unless subclassing# Scoped directly. This option is NOT inherited by subclasses.inherit_stack=False# Maximum number of scopes that can be nested on this stack.# This cannot be overridden if inheriting the parent stack.max_nesting=16# If True, instances can be re-opened after being closed.# If False, instances can only be opened and closed once, and will# raise a LifecycleError on any attempt to reopen them.allow_reuse=FalseDefault InstanceAn instance of a Scoped subclass can be assigned to thedefaultproperty
of the class. This instance will be the value of thecurrentproperty
when the stack is empty i.e. when no other instances are open. The default
instance itself is not opened by virtue of being the default. Opening it
will push it onto the stack like any other instance.ErrorsScopedhas three inner exception classes that it will raise for various
error conditions:Scoped.Erroris the base class for the other two, which
areScoped.MissingandScoped.Lifecycle.Scoped.Missingis raised when an attempt is made to access a scoped object
that is not available, i.e. when accessingScoped.currentwith an empty
stack and no default instance.Scoped.Lifecycleis raised on any attempt to open or close a scoped object
at the wrong time e.g. opening an object that is already open, closing an object
that is not at the top of the stack, and various other cases.Both of these exceptions are automatically subclassed along with their containing
class. Each subclass ofScopedgets its own exception classes that inherit
from the base exceptions. This allows you to easily handle errors from particular
scoped classes without worrying about catching unrelated errors from other scoped
classes.DocsThe complete documentation for depocs can be found on readthedocs.orgFAQQ: What does the name “depocs” mean?A: It’s “scoped” spelled backwards. :smile: