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 Union types again #41

Closed
SvenWarnke opened this issue Mar 2, 2023 · 1 comment
Closed

Support Union types again #41

SvenWarnke opened this issue Mar 2, 2023 · 1 comment

Comments

@SvenWarnke
Copy link
Contributor

SvenWarnke commented Mar 2, 2023

Consider the scenario, where an argument could have one of multiple types (see code below). Under version 0.2.1 this code worked. Now under 1.0.0 it breaks with "TypeError: Union types other than 'Optional' are not supported"

from dataclasses import dataclass, field
from typing import Union
from argparse_dataclass import ArgumentParser


def str_or_int(value: str) -> Union[str, int]:
    try:
        return int(value)
    except ValueError:
        return value


@dataclass
class Options:
    str_or_int: Union[str, int] = field(metadata=dict(type=str_or_int))


parser = ArgumentParser(Options)
print(parser.parse_args(["--str-or-int", "John"]))
print(parser.parse_args(["--str-or-int", "42"]))

I think this is a legitimate use case and by having the 'type' field in metadata the user can take up the burden of transforming those. We are currently using argparse-dataclass 0.2.1 with Union types so this change in behavior is preventing us from updating at the moment.

It would be great to have this support for Union because I would really like to update and get support for Optional types as well.

@SvenWarnke SvenWarnke mentioned this issue Mar 2, 2023
@mivade
Copy link
Owner

mivade commented Mar 7, 2023

Closed via #42.

@mivade mivade closed this as completed Mar 7, 2023
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants