Belle II Software development
utilities.py
1#!/usr/bin/env python3
2
3
10
11import sys
12import argparse
13
14
15class DefaultHelpArgumentParser(argparse.ArgumentParser):
16
17 """An argparse.Argument parse slightly changed such
18 that it always prints an extended help message in case of a parsing error."""
19
20 def error(self, message):
21 """Method invoked when a parsing error occurred.
22 Writes an extended help over the base ArgumentParser.
23 """
24 self.print_help()
25 sys.stderr.write(f'error: {message}\n')
26 sys.exit(2)
27
28
29class NonstrictChoices(list):
30
31 """Class that instances can be given to an argparse.ArgumentParser.add_argument as choices keyword argument.
32
33 The explicit choices stated during construction of this object are just suggestions but all other values are
34 excepted as well.
35 """
36
37 def __contains__(self, value):
38 """Test for correctness of the choices.
39 Always returns true since all choices should be valid not only the ones stated at construction of this object.
40 """
41 return True
42
43 def __iter__(self):
44 """Displays all explicit values and a final "..." to indicate more choices might be possible."""
45 # Append an ellipses to indicate that there are more choices.
46 copy = list(super().__iter__())
47 copy.append('...')
48 return iter(copy)
49
50 def __str__(self):
51 """Displays all explicit values and a final "..." to indicate more choices might be possible."""
52 # Append an ellipses to indicate that there are more choices.
53 copy = list(self)
54 copy.append('...')
55 return str(copy)