Skip to content

Commit

Permalink
Fix bug for defaults set to dataclass types
Browse files Browse the repository at this point in the history
  • Loading branch information
brentyi committed Sep 1, 2022
1 parent f5c2865 commit 6356df9
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 2 deletions.
6 changes: 4 additions & 2 deletions dcargs/_fields.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,7 +530,7 @@ def _ensure_dataclass_instance_used_as_default_is_frozen(
frozen."""
assert dataclasses.is_dataclass(default_instance)
cls = type(default_instance)
if not cls.__dataclass_params__.frozen:
if not cls.__dataclass_params__.frozen: # type: ignore
warnings.warn(
f"Mutable type {cls} is used as a default value for `{field.name}`. This is"
" dangerous! Consider using `dataclasses.field(default_factory=...)` or"
Expand Down Expand Up @@ -566,7 +566,9 @@ def _get_dataclass_field_default(
# Try grabbing default from dataclass field.
if field.default not in MISSING_SINGLETONS:
default = field.default
if dataclasses.is_dataclass(default):
# Note that dataclasses.is_dataclass() will also return true for dataclass
# _types_, not just instances.
if type(default) is not type and dataclasses.is_dataclass(default):
_ensure_dataclass_instance_used_as_default_is_frozen(field, default)
return default

Expand Down
13 changes: 13 additions & 0 deletions tests/test_dcargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -468,6 +468,19 @@ def main(x: Callable[[int], int] = lambda x: x * 2) -> Callable[[int], int]:
dcargs.cli(main, args=["--x", "something"])


def test_fixed_dataclass_type():
@dataclasses.dataclass
class Dummy:
pass

def main(x: Callable = Dummy) -> Callable:
return x

assert dcargs.cli(main, args=[]) is Dummy
with pytest.raises(SystemExit):
dcargs.cli(main, args=["--x", "something"])


def test_missing_singleton():
assert dcargs.MISSING is copy.deepcopy(dcargs.MISSING)

Expand Down

0 comments on commit 6356df9

Please sign in to comment.