Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you delete an argument from a namespace

Question: Given an argparse parser instance with some arguments added, is there a way to delete/remove an argument defined for it?

Why: Considering the exemple below:

>>>import argparse
>>>parser = argparse.ArgumentParser()
>>>parser.add_argument('--imagePath', action = "store", default = 'toto')
_StoreAction(option_strings=['--imagePath'], dest='imagePath', nargs=None, const=None, default='toto', type=None, choices=None, help=None, metavar=None)
>>>args = parser.parse_args()
>>>args
Namespace(imagePath='toto')
>>>parser.add_argument('--resultPath', action = "store", default = 'titi')
_StoreAction(option_strings=['--resultPath'], dest='resultPath', nargs=None, const=None, default='titi', type=None, choices=None, help=None, metavar=None)
>>>args = parser.parse_args()
>>>args
Namespace(imagePath='toto', resultPath='titi')

If we will, later in the script, change the value of the args.imagePath?

I does not found a method for change the value, but if I can delete / remove the argument imagePath it could be possible to define again imagePath with a new value !

like image 650
servoz Avatar asked Nov 09 '15 17:11

servoz


2 Answers

To delete an argparse argument, one can use the oneliner

imagePath = args.__dict__.pop('imagePath')

Here the deleted value is even stored at the same time in a new variable.

If the deleted value is not needed at all, then just:

del args.imagePath
like image 35
Friedrich Avatar answered Nov 10 '22 19:11

Friedrich


Just do:

args.imagePath = 'newvalue'

args is an argparse.Namespace object. This is a simple class, that just adds a display method - what you see with print(args). Otherwise, all the normal Python object methods work. So you can fetch, set, even add attributes as desired.

The parser tries to keep its assumptions about the namespace object to a minimum. It uses the most generic access methods - hasattr, getattr, setattr.

e.g.

dest = 'imagePath'
value = 'newvalue'
setattr(args, dest, value)

You can also delete, e.g.

del args.imagePath
delattr(args, 'imagePath')

I'm tempted to change your title to 'How do you delete an argument from a namespace'. I don't think you mean to delete the argument (Action created by add_argument) from the parser itself. Your focus is on the namespace created by parsing.

like image 166
hpaulj Avatar answered Nov 10 '22 17:11

hpaulj