How to use the dacite.dataclasses.get_default_value_for_field function in dacite

To help you get started, we’ve selected a few dacite examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github konradhalas / dacite / tests / test_dataclasses.py View on Github external
def test_get_default_value_for_field_with_default_factory():
    @dataclass
    class X:
        i: int = field(default_factory=lambda: 1)

    value = get_default_value_for_field(field=fields(X)[0])

    assert value == 1
github konradhalas / dacite / tests / test_dataclasses.py View on Github external
def test_get_default_value_for_field_with_default_value():
    @dataclass
    class X:
        i: int = 1

    value = get_default_value_for_field(field=fields(X)[0])

    assert value == 1
github konradhalas / dacite / tests / test_dataclasses.py View on Github external
def test_get_default_value_for_optional_field():
    @dataclass
    class X:
        i: Optional[int]

    value = get_default_value_for_field(field=fields(X)[0])

    assert value is None
github konradhalas / dacite / tests / test_dataclasses.py View on Github external
def test_get_default_value_for_field_without_default_value():
    @dataclass
    class X:
        i: int

    with pytest.raises(DefaultValueNotFoundError):
        get_default_value_for_field(field=fields(X)[0])
github konradhalas / dacite / dacite / core.py View on Github external
field.type = data_class_hints[field.name]
        try:
            try:
                field_data = data[field.name]
                transformed_value = transform_value(
                    type_hooks=config.type_hooks, cast=config.cast, target_type=field.type, value=field_data
                )
                value = _build_value(type_=field.type, data=transformed_value, config=config)
            except DaciteFieldError as error:
                error.update_path(field.name)
                raise
            if config.check_types and not is_instance(value, field.type):
                raise WrongTypeError(field_path=field.name, field_type=field.type, value=value)
        except KeyError:
            try:
                value = get_default_value_for_field(field)
            except DefaultValueNotFoundError:
                if not field.init:
                    continue
                raise MissingValueError(field.name)
        if field.init:
            init_values[field.name] = value
        else:
            post_init_values[field.name] = value

    return create_instance(data_class=data_class, init_values=init_values, post_init_values=post_init_values)