當前位置: 首頁>>代碼示例>>Python>>正文


Python dataclasses.InitVar方法代碼示例

本文整理匯總了Python中dataclasses.InitVar方法的典型用法代碼示例。如果您正苦於以下問題:Python dataclasses.InitVar方法的具體用法?Python dataclasses.InitVar怎麽用?Python dataclasses.InitVar使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在dataclasses的用法示例。


在下文中一共展示了dataclasses.InitVar方法的13個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: _contains_non_default_init_vars

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def _contains_non_default_init_vars(cls, previous_classes=None):
        """Check whether this dataclass contains non-default init-only vars.

        Performs a recursive check through all fields that are declared as
        dataclasses to ensure that no nested dataclasses contain init-only
        variables. The ``previous_classes`` argument is a set of previously
        checked classes to prevent infinite recursion on recursive structures.

        :param previous_classes: The set of previously checked classes.
        """
        try:
            previous_classes.add(cls)
        except AttributeError:  # NoneType
            previous_classes = {cls}

        # The identify check (.. is MISSING) is fine, MISSING is a singleton
        has_init_vars = any(field.type == InitVar and field.default is MISSING
                            for field in cls.__dataclass_fields__.values())
        children_have_init_vars = any(
                child.type._contains_non_default_init_vars(previous_classes)
                for child in fields(cls)
                if (is_dataclass(child.type)
                    and child.type not in previous_classes))
        return has_init_vars or children_have_init_vars 
開發者ID:abatilo,項目名稱:typed-json-dataclass,代碼行數:26,代碼來源:typed_json_dataclass.py

示例2: test_initvars_post_init

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_initvars_post_init():
    @pydantic.dataclasses.dataclass
    class PathDataPostInit:
        path: Path
        base_path: dataclasses.InitVar[Optional[Path]] = None

        def __post_init__(self, base_path):
            if base_path is not None:
                self.path = base_path / self.path

    path_data = PathDataPostInit('world')
    assert 'path' in path_data.__dict__
    assert 'base_path' not in path_data.__dict__
    assert path_data.path == Path('world')

    with pytest.raises(TypeError) as exc_info:
        PathDataPostInit('world', base_path='/hello')
    assert str(exc_info.value) == "unsupported operand type(s) for /: 'str' and 'str'" 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:20,代碼來源:test_dataclasses.py

示例3: test_initvars_post_init_post_parse

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_initvars_post_init_post_parse():
    @pydantic.dataclasses.dataclass
    class PathDataPostInitPostParse:
        path: Path
        base_path: dataclasses.InitVar[Optional[Path]] = None

        def __post_init_post_parse__(self, base_path):
            if base_path is not None:
                self.path = base_path / self.path

    path_data = PathDataPostInitPostParse('world')
    assert 'path' in path_data.__dict__
    assert 'base_path' not in path_data.__dict__
    assert path_data.path == Path('world')

    assert PathDataPostInitPostParse('world', base_path='/hello').path == Path('/hello/world') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:18,代碼來源:test_dataclasses.py

示例4: _is_initvar_type

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def _is_initvar_type(the_type: Callable[..., TypeT]) -> bool:
    """Return True if the type is an InitVar

    In Python 3.7, InitVar is essentially a singleton.
        InitVar[str] == InitVar[int]
    In Python 3.8, InitVar can be a singleton, or an instance.
        InitVar[str] != InitVar[int], but InitVar == InitVar

    Therefore, the code below checks for both cases to support 3.7 and 3.8
    """
    if VER_3_7_AND_UP:
        return the_type == InitVar or isinstance(the_type, InitVar)  # type: ignore
    return False 
開發者ID:Dobiasd,項目名稱:undictify,代碼行數:15,代碼來源:_unpack.py

示例5: test_is_init_var_with_init_var

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_is_init_var_with_init_var():
    assert is_init_var(InitVar[int]) 
開發者ID:konradhalas,項目名稱:dacite,代碼行數:4,代碼來源:test_types.py

示例6: test_is_instance_with_init_var_and_matching_value_type

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_is_instance_with_init_var_and_matching_value_type():
    assert is_instance(1, InitVar[int]) 
開發者ID:konradhalas,項目名稱:dacite,代碼行數:4,代碼來源:test_types.py

示例7: test_is_instance_with_init_var_and_not_matching_value_type

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_is_instance_with_init_var_and_not_matching_value_type():
    assert not is_instance(1, InitVar[str]) 
開發者ID:konradhalas,項目名稱:dacite,代碼行數:4,代碼來源:test_types.py

示例8: test_from_dict_with_init_var

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_from_dict_with_init_var():
    @dataclass
    class X:
        a: InitVar[int]
        b: Optional[int] = None

        def __post_init__(self, a: int) -> None:
            self.b = 2 * a

    result = from_dict(X, {"a": 2})

    assert result.b == 4 
開發者ID:konradhalas,項目名稱:dacite,代碼行數:14,代碼來源:test_init_var.py

示例9: is_init_var

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def is_init_var(type_: Type) -> bool:
    return isinstance(type_, InitVar) or type_ is InitVar 
開發者ID:konradhalas,項目名稱:dacite,代碼行數:4,代碼來源:types.py

示例10: test_init_vars

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_init_vars():

    @dataclass
    class DataClass(DataClassDictMixin):
        x: InitVar[int] = None
        y: int = None

        def __post_init__(self, x: int):
            if self.y is None and x is not None:
                self.y = x

    assert DataClass().to_dict() == {'y': None}
    assert DataClass(x=1).to_dict() == {'y': 1}
    assert DataClass.from_dict({}) == DataClass()
    assert DataClass.from_dict({'x': 1}) == DataClass() 
開發者ID:Fatal1ty,項目名稱:mashumaro,代碼行數:17,代碼來源:test_data_types.py

示例11: is_init_var

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def is_init_var(t):
    if PY_36 or PY_37:
        return get_type_origin(t) is dataclasses.InitVar
    elif PY_38:
        return isinstance(t, dataclasses.InitVar)
    else:
        raise NotImplementedError 
開發者ID:Fatal1ty,項目名稱:mashumaro,代碼行數:9,代碼來源:helpers.py

示例12: test_initvar

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_initvar():
    InitVar = dataclasses.InitVar

    @pydantic.dataclasses.dataclass
    class TestInitVar:
        x: int
        y: InitVar

    tiv = TestInitVar(1, 2)
    assert tiv.x == 1
    with pytest.raises(AttributeError):
        tiv.y 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:14,代碼來源:test_dataclasses.py

示例13: test_derived_field_from_initvar

# 需要導入模塊: import dataclasses [as 別名]
# 或者: from dataclasses import InitVar [as 別名]
def test_derived_field_from_initvar():
    InitVar = dataclasses.InitVar

    @pydantic.dataclasses.dataclass
    class DerivedWithInitVar:
        plusone: int = dataclasses.field(init=False)
        number: InitVar[int]

        def __post_init__(self, number):
            self.plusone = number + 1

    derived = DerivedWithInitVar(1)
    assert derived.plusone == 2
    with pytest.raises(TypeError):
        DerivedWithInitVar('Not A Number') 
開發者ID:samuelcolvin,項目名稱:pydantic,代碼行數:17,代碼來源:test_dataclasses.py


注:本文中的dataclasses.InitVar方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。