Skip to content

Commit

Permalink
do not add type of default if it is already in type
Browse files Browse the repository at this point in the history
  • Loading branch information
njzjz authored Oct 25, 2023
1 parent fb3cd72 commit 0a15484
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
15 changes: 14 additions & 1 deletion dargs/dargs.py
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ 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 +968,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
2 changes: 1 addition & 1 deletion dargs/sphinx.py
Original file line number Diff line number Diff line change
Expand Up @@ -192,5 +192,5 @@ 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"], doc="Argument 3"),
]

0 comments on commit 0a15484

Please sign in to comment.