作用域线程本地混合类
depocs的Python项目详细描述
^ tt1}$是一个为每个线程创建线程本地堆栈的混合类。 子类。子类的实例可以在此堆栈上推送和弹出, 堆栈顶部的实例始终可用作 全班同学。Scoped类通常用于隐式地生成参数 在(动态)范围内可用,而不必将它们作为 函数参数。Scoped帮助您以安全和方便的方式执行此操作, 当你做错事的时候会提供非常有用的错误信息。
示例
可以使用Scoped类传递上下文数据:
classSession(Scoped):def__init__(self,user):self.user=userdefprint_current_user():print(Session.current.user)withSession(some_guy):print_current_user()
它还可用于提供依赖项:
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 time
打开和关闭
Scoped对象最好用作上下文管理器(即使用with 语句),但对于不可能这样做的情况,也可以打开 并“手动”关闭它们:
classTransaction(Scoped):...transaction=Transaction().open()try:...finally:transaction.close()
显然,你需要做一切必要的事情来确保 对open的调用与对close的调用匹配。
选项
Scoped子类的行为可以通过声明 名为ScopedOptions的嵌套类中的选项。除非另有说明, 选项由不重写的子类自动继承 他们:
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=False
默认实例
作用域子类的实例可以分配给default属性 在班上。此实例将是current属性的值 当堆栈为空时,即当没有其他实例打开时。违约 实例本身不是由于默认而打开的。打开它 会像其他实例一样将其推送到堆栈上。
错误
Scoped有三个内部异常类,它将为不同的 错误条件:Scoped.Error是其他两个的基类,其中 是Scoped.Missing和Scoped.Lifecycle。
Scoped.Missing在试图访问作用域对象时引发 这是不可用的,即当使用空的 堆栈,没有默认实例。
Scoped.Lifecycle在试图打开或关闭作用域对象时引发 在错误的时间打开一个已经打开的对象,关闭一个对象 这不在堆栈的顶部,还有其他各种情况。
这两个异常都会自动子类化,并包含 上课。Scoped的每个子类都有自己的异常类,这些类继承 从基本异常。这允许您轻松处理来自 作用域类,而不必担心从其他作用域捕获不相关的错误 上课。
常见问题解答
问:“仓库”这个名字是什么意思?
A:它的“scoped”拼写是向后的。:微笑: