argparse - disable same argument occurrences

I don't think there is a native way to do it using argparse, but fortunately, argparse offers methods to report custom errors. The most elegant way is probably to define a custom action that checks for duplicates (and exits if there are).

class UniqueStore(argparse.Action):
    def __call__(self, parser, namespace, values, option_string):
        if getattr(namespace, self.dest, self.default) is not self.default:
            parser.error(option_string + " appears several times.")
        setattr(namespace, self.dest, values)

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', action=UniqueStore)

args = parser.parse_args()

(Read the docs about cutom actions)

Another way is to use the append action and count the len of the list.

parser = argparse.ArgumentParser()
parser.add_argument('-f', '--foo', action='append')
args = parser.parse_args()

if len(args.foo) > 1:
    parser.error("--foo appears several times.")

There's no built in test or constraint. A positional argument will be handled only once, but the flagged (or optional) ones can, as you say, be repeated. This lets you collect multiple occurrences with append or count actions.

The override action is acceptable to most people. Why might your user use the option more than once? Why should the first be preferred over the last?

A custom Action may be the best choice. It could raise an error if the namespace[dest] already has a non-default value. Or this Action could add some other 'repeat' flag to the namespace.