gluonts.core.settings 模块#
gluonts.core.settings#
此模块提供了一个 Settings 类,允许管理全局上下文。
其思想是支持一种依赖注入形式,其中不是沿着调用链传递具体的值,而是通过设置进行共享。
gluonts.env 是一个 Settings。
示例
from gluonts.core.settings import Settings
class MySettings(Settings):
debug: bool = False
settings = MySettings()
def fn():
if settings.debug:
print("In debug mode.")
with settings._let(debug=True):
# this will print the message
fn()
# no message will be printed
fn()
另一种选择是将上下文注入到函数中。这样做的好处是,你仍然可以手动传递值,但可以使用上下文作为备用
@settings._inject("debug")
def fn(debug):
...
# this will use the value defined in the context
fn()
# but one can still set the value manually
fn(False)
可以通过 getitem (setting[“name”]) 和 getattr (setting.name) 两种方式访问值。为了避免可能的名称冲突,Settings 上的所有方法都使用前导下划线(例如 settings._let)。因此,键不允许以下划线开头。
Settings 包含一个默认字典,可以直接设置它,并且 _declare 会使用它。
此外,可以声明一个类型,并使用 pydantic 进行检查。每当设置新值时,都会进行类型检查。
- class gluonts.core.settings.LinkedList(elements=())[source]#
基类:
object
简单的链表,其中只有元素控制它们的移除。
当退出 let 块时,压入的环境应该被销毁,而不仅仅是堆栈的最后一个元素。