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 add_argument type parameter #23

Closed
reidswanson opened this issue Jan 30, 2023 · 1 comment
Closed

Support add_argument type parameter #23

reidswanson opened this issue Jan 30, 2023 · 1 comment

Comments

@reidswanson
Copy link

reidswanson commented Jan 30, 2023

With argparse.add_argument it is possible to convert the argument passed on the command line to a different type. It would be useful to have this functionality using datargs, but does not seem possible (e.g., type is not a supported keyword for the arg utility function).

For example, I have a command line option for setting the log level. I would like the end user to be able to specify the level using its name, a string, but stored in the dataclass as an int so that it can be directly used to setup the logging configuration.

It's certainly possible to do the conversion afterwards, but it would be more convenient to have the transformation done during parsing. Currently, I might reuse the same arguments dataclass in multiple programs, which requires me to apply the type transformation in each program, versus having it done transparently by the parser.

[Edit]
One other thing that doing the conversion client side makes less convenient are choices. Using the type conversion with argparse it is easy to make string choices case insensitive, but doing it client side requires the command line argument to match the case exactly.

@roee30
Copy link
Owner

roee30 commented Feb 1, 2023

datargs is meant to express a simple equivalence between dataclasses and argument parsers so it is not meant for this use. If you can reuse the dataclass, you can also reuse the same utility functions - setting the log level, just converting between the parser dataclass and a slightly different one, or whatever else you choose.

Note that you can create a custom class to mimic argparse's behavior, although I would generally advise against it:

from dataclasses import dataclass
import datargs
import logging


class Level(int):
    def __new__(cls, level):
        try:
            return logging._nameToLevel[level]
        except KeyError:
            raise TypeError(f'invalid logging level {level}')


@dataclass
class Args:
    level: Level


print(datargs.parse(Args, ['--level', 'DEBUG']))

This should work properly both at runtime and with static type checking.

@roee30 roee30 closed this as completed Feb 1, 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