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

Integration with argparse #11

Closed
mheppner opened this issue Mar 29, 2018 · 1 comment
Closed

Integration with argparse #11

mheppner opened this issue Mar 29, 2018 · 1 comment

Comments

@mheppner
Copy link

I have a use-case where I need to support both command-line arguments, as well as environment variables. This pattern ends up looking like this:

def parse_env():
    env = Env()
    return {
        'my_option': env.str('MY_OPTION', default='value'),
        'positional': env.str('POSITIONAL')
        'many_inputs': env.list('MANY_INPUTS')
    }

def parse_cli():
    parser = argparse.ArgumentParser()
    parser.add_argument('-m', '--my-option', default='value')
    parser.add_argument(dest='positional')
    parser.add_argument(dest='many_inputs', nargs='+')
    return vars(parser.parse_args())

if __name__ == '__main__':
    if os.environ.get('USE_ENV'):
        args = parse_env()
    else:
        args = parse_cli()

    do_something(**args)

Is there a better pattern for this? There's a lot of duplicate logic, making sure both variables are the same and defaults match. Could this be a feature request to add this to argparse, maybe with a subclass?

I'm thinking something like this:

from environs import EnvArgumentParser
parser = EnvArgumentParser(
    env_prefix='MY_PREFIX_'  # this would be neat
)
parser.add_argument('-m', '--my-option', default='value', env_name='MY_OPTION')
parser.add_argument(dest='positional', env_name='CUSTOM_NAME')
parser.add_argument(dest='many_inputs', nargs='+')  # default env_name to MANY_INPUTS

Thoughts? If you think this would be useful for this library, I can try working on it. I don't know the internals of argparse very well though.

@sloria
Copy link
Owner

sloria commented May 8, 2018

The EnvArgumentParser idea seems neat, but I think it's outside the scope of this library. Would definitely be cool to see as a separate package, though. Thanks for the suggestion.

@sloria sloria closed this as completed May 8, 2018
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