1

I am using the argparse module in Python3. The result of the parsed arguments are given back as a Namespace object. But I want to have them in the current namespace and not a different one.

#!/usr/bin/env python3
import argparse

parser = argparse.ArgumentParser(description='desc')
parser.add_argument('--profile', dest='profile_name', help='help')

# I need the magic here    
print( parser.parse_args(namespace=self) )
print(profile_name)

Is there a way to handle this? Or do I have to make it myself manually like this:

args = parser.parse_args()
profile_name = args.profile_name

2 Answers 2

3

You may be confusing 2 uses of 'namespace'.

One namespace is the dictionary that holds the variables of this module or function.

parser.parse_args() creates an argparse.Namespace object, and puts its values in it, using setattr. This class definition is pretty simple.

parser.parse_args(namespace=myNamespace) should work with any object that accepts the setattr, getattr and hasattr methods. A dictionary does not work.

If given a dictionary the first error I get is in

setattr(namespace, action.dest, default)
AttributeError: 'dict' object has no attribute 'checked'

Are you asking this because you want to put the argparse attributes directly in the local namespace dictionary?

You can convert a Namespace to a dictionary with vars(args). And you can add those items to another dictionary with update (e.g. locals().update(vars(args)) ).

Or if you have a function that takes **kwargs, you could use: foo(**vars(args)) to put those arguments into the function's namespace. This does a better job of localizing the change. It also lets you define the variables with the normal keyword syntax.

Sign up to request clarification or add additional context in comments.

Comments

1

I do not recommend this since it can override previously defined variables, especially if all you want is avoid typing a couple of characters, but you can add variables to the global scope like this:

args = parser.parse_args()

for k, v in args.__dict__.items():
    globals()[k] = v
print(profile_name)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.