创建模型时使用 Python 的 attr 包的动态默认值

问题描述 投票:0回答:0

我正在与 attr 一起创建一个元模型(展示一个子集来给出想法),


import abc, attr
from attrs import validators
from delensalot.lerepi.core.validator import model

@attr.s
class DLENSALOT_Data:
    """A root model element of the Dlensalot formalism.

    Attributes:
        beam: 
    """

    beam = attr.ib(default=None)



@attr.s
class DLENSALOT_Model:
    """A root model element of the Dlensalot formalism.

    Attributes:
        data: 
    """
    
    data  = attr.ib(default=DLENSALOT_Data(), validator=model.data)

一个模型,

DLENSALOT_Model()
然后默认为预期的默认值。

我想根据用户的选择有一个不同的默认配置,在以下意义上:

DLENSALOT_Model(defaultsto='A').data.beam
>>> <beam value for default A>
DLENSALOT_Model(defaultsto='B').data.beam
>>> <beam value for default B>

换句话说,我想要一种配置元模型的方法。我在想类似的东西(这不起作用,但我希望它能给出想法),


import abc, attr
from attrs import validators
from delensalot.lerepi.core.validator import model

default_dict = {
    'A' : ...,
    'B': ...
}


@attr.s
class DLENSALOT_Data:
    """A root model element of the Dlensalot formalism.

    Attributes:
        beam: 
    """
    defaultsto = attr.ib()
    beam = attr.ib(default=default_dict[defaultsto]['data']['beam'])



@attr.s
class DLENSALOT_Model(DLENSALOT_Concept):
    """A root model element of the Dlensalot formalism.

    Attributes:
        data: 
    """
    defaultsto = attr.ib()
    data  = attr.ib(default=DLENSALOT_Data(defaultsto=defaultsto), validator=model.data)

任何建议表示赞赏

我试过

attr.Factory(lambda self: .., takes_self - True)
,装饰器后设置默认值,它只是不适合我..

python attr
© www.soinside.com 2019 - 2024. All rights reserved.