Use Python Dictionary argparse

I have a dictionary that maps human-readable values ​​to three different Python values. As an argparse module, Python uses this dictionary to get specific values ​​when the user can choose between keys.

I currently have this:

def parse(a):
    values = { "on": True, "off": False, "switch": None }
    parser = argparse.ArgumentParser()
    parser.add_argument("-v", "--value", choices=values, default=None)
    args = parser.parse_args(a)
    print("{}: {}".format(type(args.value), args.value))

>>> parse(['-v', 'on'])
<type 'str'>: on
>>> parse(['-v', 'off'])
<type 'str'>: off
>>> parse(['-v', 'switch'])
<type 'str'>: switch
>>> parse([])
<type 'NoneType'>: None

The problem is that argparse does not return True, Falseor Noneif a parameter is given. Is there an easy way to add this feature? Of course, after that I can do something like this:

args.value = values[args.value]

, , ( , None "switch"). , .

+4
3

args.value = values.get(args.values)

None dict (, ).

type argparse:

values = { "on": True, "off": False, "switch": None }
def convertvalues(value):
    return values.get(value)
parser.add_argument('-v','--value',type=convertvalues)

"" , , . :

def convertvalues(value):
     return values.get(value,value)
parser.add_argument('-v','--value',type=convertvalues,
                                   choices=[True,False,None],
                                   default=None)

convertvalues ​​ , 'on', 'off', 'switch' None , - (, 'bla'). "bla" , .

"" , argparse. , docs:

class DictAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        value_dict = { "on": True, "off": False, "switch": None }
        setattr(namespace, self.dest, value_dict.get(values))
parser.add_argument('-v','--value',action=DictAction,
                                   choices=['on','off','switch'],
                                   default=None)

, , Acion init, hardcoded value_dict.

+3
values = { "on": True, "off": False, "switch": None }
parser.add_argument("-v", "--value", choices=values.keys())
value = values.get(args.value)
0

"oekopez", , add_argument.

class DictAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        setattr(namespace, self.dest, self.choices.get(values, self.default))

value_dict = { "on": True, "off": False, "switch": None }
parser.add_argument('-v','--value',action=DictAction,
                               choices=value_dict,
                               default=None)
0

Source: https://habr.com/ru/post/1533339/


All Articles