Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python argparse: Force a list item to be unique

Being able to validate the list items using choices=servers below is nice.

servers = [ "ApaServer", "BananServer", "GulServer", "SolServer", "RymdServer", "SkeppServer", "HavsServer", "SovServer" ]
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--only', nargs='*', choices=servers, help='Space separated list of case sensitive server names to process')

Is it possible to force an item in the list to be unique, so that no duplicates are allowed?

like image 781
Deleted Avatar asked Dec 16 '22 03:12

Deleted


1 Answers

The way to properly discard duplicates using argparse would be to create your own argparse.Action class that takes care of using set as suggestted by other answers:

import argparse

class UniqueAppendAction(argparse.Action):
    def __call__(self, parser, namespace, values, option_string=None):
        unique_values = set(values)
        setattr(namespace, self.dest, unique_values)

servers = ["ApaServer", "BananServer", "GulServer", "SolServer",
           "RymdServer", "SkeppServer", "HavsServer", "SovServer" ]
parser = argparse.ArgumentParser()
parser.add_argument('-o', '--only', nargs='*', choices=servers, action=UniqueAppendAction,
                    help='Space separated list of case sensitive server names to process')
print parser.parse_args()

Example output:

$ python test.py -o ApaServer ApaServer
Namespace(only=set(['ApaServer']))
like image 69
jcollado Avatar answered Jan 04 '23 01:01

jcollado