Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

do not add type of default if it is already in type #40

Merged
merged 6 commits into from
Oct 25, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion dargs/dargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,11 @@ def _reorg_dtype(self):
# check conner cases
if self.sub_fields or self.sub_variants:
self.dtype.add(list if self.repeat else dict)
if self.optional and self.default is not _Flags.NONE:
if (
self.optional
and self.default is not _Flags.NONE
and all([not isinstance_annotation(self.default, tt) for tt in self.dtype])
):
self.dtype.add(type(self.default))
# and make it compatible with `isinstance`
self.dtype = tuple(self.dtype)
Expand Down Expand Up @@ -968,6 +972,19 @@ def trim_by_pattern(
argdict.pop(key)


def isinstance_annotation(value, dtype) -> bool:
"""Same as isinstance(), but supports arbitrary type annotations."""
try:
typeguard.check_type(
value,
dtype,
collection_check_strategy=typeguard.CollectionCheckStrategy.ALL_ITEMS,
)
except typeguard.TypeCheckError as e:
return False
return True


class ArgumentEncoder(json.JSONEncoder):
"""Extended JSON Encoder to encode Argument object:

Expand Down
8 changes: 7 additions & 1 deletion dargs/sphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,11 @@ def _test_arguments() -> List[Argument]:
return [
Argument(name="test1", dtype=int, doc="Argument 1"),
Argument(name="test2", dtype=[float, None], doc="Argument 2"),
Argument(name="test3", dtype=List[str], doc="Argument 3"),
Argument(
name="test3",
dtype=List[str],
default=["test"],
optional=True,
doc="Argument 3",
),
]
3 changes: 3 additions & 0 deletions tests/test_checker.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,9 @@ def test_name_type(self):
# list[int]
ca = Argument("key1", List[float])
ca.check({"key1": [1, 2.0, 3]})
with self.assertRaises(ArgumentTypeError):
ca.check({"key1": [1, 2.0, "3"]})
ca = Argument("key1", List[float], default=[], optional=True)
with self.assertRaises(ArgumentTypeError):
ca.check({"key1": [1, 2.0, "3"]})
# optional case
Expand Down
Loading