Search code examples
pythonargumentsargparse

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 !


Solution

  • 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.