簡體   English   中英

基於 attr.s 的 hydra 結構化配置中的屬性轉換器

[英]Attribute Converter in attr.s-based hydra Structured Configs

是否可以在基於attr.shydra結構的配置中使用轉換器

我用這個最小的例子試了一下:

import hydra
from hydra.core.config_store import ConfigStore
import attr

@attr.s
class Times10Config:
    num: int = attr.ib(default=42, converter=lambda x: x*10)

cs = ConfigStore.instance()
# Registering the Config class with the name 'config'.
cs.store(name="config", node=Times10Config)

@hydra.main(version_base=None, config_name="config")
def my_app(cfg: Times10Config) -> None:
    print(cfg)

if __name__ == "__main__":
    my_app()

但是跑步

python -m my_app num=1

結果為 output:

{'num': 1}

在 python 解釋器中直接實例化Times10Config確實會導致預期的行為:

In [5]: Times10Config(num=1)
Out[5]: Times10Config(num=10)

OmegaConf 不實例化底層對象——它只是將它們用作運行時驗證的描述符。 數據類/屬性 class 中定義的任何邏輯均未正常運行。

您可以使用OmegaConf.to_object()將配置結構轉換為本機對象。 請務必閱讀OmegaConf.to_container()的文檔。

在 Hydra 應用程序的上下文中,您可以在運行開始時轉換配置:

@hydra.main(version_base=None, config_name="config")
def my_app(cfg: Times10Config) -> None:
    cfg = OmegaConf.to_object(cfg)
    print(cfg)

不是自動的,但您可以添加以下行:

    cfg = Times10Config(**cfg)

to instantiate an object of the config class from the object that is passed to the hydra.main -decorated function if you want to actually get a config object of your defined class, and have all the normal attrs mechanisms (validators, converters, etc. ) to kick in. But the object that is passed by hydra is actually just a DictConfig object and that type annotation is just used to make the static type checker verify the attributes of the config object.

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM