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

Support __futre__.annotations #51

Open
wants to merge 5 commits into
base: main
Choose a base branch
from
Open
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
16 changes: 15 additions & 1 deletion argparse_dataclass.py
Original file line number Diff line number Diff line change
Expand Up @@ -316,13 +316,27 @@ def parse_known_args(
return options_class(**kwargs), others


def _fields(options_class: typing.Type[OptionsType]) -> typing.Tuple[Field, ...]:
mivade marked this conversation as resolved.
Show resolved Hide resolved
"""Get tuple of Field for dataclass."""
type_hints = typing.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_hints[_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:
if not is_dataclass(options_class):
raise TypeError("cls must be a dataclass")

for field in fields(options_class):
for field in _fields(options_class):
args = field.metadata.get("args", [f"--{field.name.replace('_', '-')}"])
positional = not args[0].startswith("-")
kwargs = {
Expand Down
23 changes: 23 additions & 0 deletions tests/test_annotations.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
from __future__ import annotations
import unittest
from argparse_dataclass import dataclass


@dataclass
class Opt:
x: int = 42
y: bool = False


class ArgParseTests(unittest.TestCase):
def test_basic(self):
params = Opt.parse_args([])
self.assertEqual(42, params.x)
self.assertEqual(False, params.y)
params = Opt.parse_args(["--x=10", "--y"])
self.assertEqual(10, params.x)
self.assertEqual(True, params.y)


if __name__ == "__main__":
unittest.main()