Skip to content

Union handles lists #308

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

Open
wants to merge 2 commits into
base: master
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
9 changes: 9 additions & 0 deletions simple_parsing/wrappers/field_wrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -330,6 +330,8 @@ def get_arg_options(self) -> dict[str, Any]:
elif self.is_union:
logger.debug("Parsing a Union type!")
_arg_options["type"] = get_parsing_fn(self.type)
if any(utils.is_list(o) for o in utils.get_args(self.type)):
_arg_options["nargs"] = "*"

elif self.is_enum:
logger.debug(f"Adding an Enum attribute '{self.name}'")
Expand Down Expand Up @@ -501,6 +503,13 @@ def postprocess(self, raw_parsed_value: Any) -> Any:
else:
return raw_parsed_value

elif self.is_union:
list_in = [utils.is_list(o) for o in utils.get_args(self.type)]
# if type is like Union[str, list[str]] and only a single value was passed,
if any(list_in) and (not all(list_in)) and (len(raw_parsed_value) == 1):
raw_parsed_value = raw_parsed_value[0]
return raw_parsed_value

elif self.is_subparser:
return raw_parsed_value

Expand Down
22 changes: 22 additions & 0 deletions test/test_union.py
Original file line number Diff line number Diff line change
Expand Up @@ -32,3 +32,25 @@ class Foo2(TestSetup):

foo = Foo2.setup("--x 2")
assert foo.x == 2 and type(foo.x) is int


def test_union_type_with_list():
@dataclass
class Foo(TestSetup):
x: Union[str, list[str]]

foo = Foo.setup("--x bob")
assert foo.x == "bob"

foo = Foo.setup("--x bob alice")
assert foo.x == ["bob", "alice"]

@dataclass
class Foo(TestSetup):
x: Union[list[int], list[str]]

foo = Foo.setup("--x bob alice")
assert foo.x == ["bob", "alice"]

foo = Foo.setup("--x 1 2")
assert foo.x == [1, 2]
Loading