Skip to content

Commit

Permalink
fix: Creation of fully un-annotated subobjects.
Browse files Browse the repository at this point in the history
  • Loading branch information
DanCardin committed Oct 30, 2023
1 parent fda5fc5 commit af3e929
Show file tree
Hide file tree
Showing 4 changed files with 32 additions and 10 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[tool.poetry]
name = "dataclass-settings"
version = "0.2.0"
version = "0.2.1"
description = "Declarative dataclass settings."

repository = "https://github.com/dancardin/dataclass-settings"
Expand Down
9 changes: 6 additions & 3 deletions src/dataclass_settings/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,11 @@ def collect(
break

if value is not None:
result[field.name] = field.map_value(value)
try:
mapped_value = field.map_value(value)
except Exception:
pass
else:
result[field.name] = mapped_value

if not result:
return None
return result
18 changes: 12 additions & 6 deletions src/dataclass_settings/class_inspect.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Field:
name: str
type: type
annotations: tuple[Any, ...]
mapper: Callable[..., Any] | None = None
mapper: Callable[..., Any]

@classmethod
def from_dataclass(cls, typ: Type) -> list[Self]:
Expand All @@ -81,6 +81,7 @@ def from_pydantic(cls, typ: Type) -> list[Self]:
name=name,
type=f.annotation,
annotations=tuple(f.metadata),
mapper=get_type(f.annotation),
)
fields.append(field)
return fields
Expand All @@ -93,6 +94,7 @@ def from_pydantic_dataclass(cls, typ: Type) -> list[Self]:
name=name,
type=f.annotation,
annotations=tuple(f.metadata),
mapper=get_type(f.annotation),
)
fields.append(field)
return fields
Expand Down Expand Up @@ -137,11 +139,9 @@ def get_nested_type(self) -> Type | None:
return supported_arg

def map_value(self, value: str | dict[str, Any]):
if self.mapper:
if isinstance(value, str):
return self.mapper(value)
return self.mapper(**value)
return value
if isinstance(value, str):
return self.mapper(value)
return self.mapper(**value)


def fields(cls: type):
Expand All @@ -159,3 +159,9 @@ def fields(cls: type):
return Field.from_attrs(cls)

raise NotImplementedError() # pragma: no cover


def get_type(typ):
if typing_inspect.is_optional_type(typ):
return get_args(typ)[0]
return typ
13 changes: 13 additions & 0 deletions tests/test_class_inspect.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
from dataclass_settings import load_settings
from pydantic import BaseModel


def test_successful_validation_of_fully_default_subobjects():
class Foo(BaseModel):
foo: int = 0

class Config(BaseModel):
foo: Foo

config = load_settings(Config)
assert config == Config(foo=Foo(foo=0))

0 comments on commit af3e929

Please sign in to comment.