Skip to content

Commit

Permalink
Support __futre__.annotations
Browse files Browse the repository at this point in the history
When importing __future__.annotations, class annotations are evaluated
lazily, and dataclasses.Field.type becomes str instead of actual type.

To access its accutual type, we patch the member.

Ref: mivade#47
  • Loading branch information
ymd-h committed Jun 6, 2023
1 parent 540640f commit 5913049
Showing 1 changed file with 14 additions and 0 deletions.
14 changes: 14 additions & 0 deletions argparse_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,6 +316,20 @@ def parse_known_args(
return options_class(**kwargs), others


def _fields(options_class: typing.Type[OptionsType]) -> typing.Tuple[Field, ...]:
"""Get tuple of Field for dataclass."""
type_hits = get_type_hints(options_class)

def _ensure_type(_f):
# When importing __future__.annotations, `Field.type` becomes `str`
# Ref: https://github.com/mivade/argparse_dataclass/issues/47
if isinstance(_f.type, str):
_f.type = type_hits[_f.name]
return _f

return tuple(_ensure_type(_f) for _f in fields(options_class))


def _add_dataclass_options(
options_class: typing.Type[OptionsType], parser: argparse.ArgumentParser
) -> None:
Expand Down

0 comments on commit 5913049

Please sign in to comment.