Is this a correct way to generate an exception when getting a wrong parameter
Peter Otten
__peter__ at web.de
Wed Aug 12 05:33:04 EDT 2015
Cecil Westerhof wrote:
> I have:
> ========================================================================
> accepted_params = {
> 'pcpu',
> 'rss',
> 'size',
> 'time',
> 'vsize',
> }
> ========================================================================
>
> Later I use:
> ========================================================================
> if (to_check != 'all') and not(to_check in accepted_params):
> raise Exception('Used illegal parameter: {0}.\n'
> 'Accepted ones: {1}'
> .format(to_check, sorted(accepted_params)))
> ========================================================================
>
> When using 'all' I want to do the work for all accepted parameters.
> ;-)
Doesn't that make it an "accepted parameter"? Why not add it to the set?
> Is this a correct way to do this, or is there a better way?
I suppose you do this early in a function? Then at least choose a more
specific exception (e. g. ValueError).
If this is about commandline arguments -- argparse can handle such
restrictions:
$ cat demo.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--check", choices=["pcpu", "rss"], default="all")
print(parser.parse_args().check)
$ python3 demo.py
all
$ python3 demo.py --check rss
rss
$ python3 demo.py --check ssr
usage: demo.py [-h] [--check {pcpu,rss}]
demo.py: error: argument --check: invalid choice: 'ssr' (choose from 'pcpu',
'rss')
More information about the Python-list
mailing list