python-console-snake
python-console-snake copied to clipboard
An invalid theme name makes program fail
If you specify a theme name in the CLI that doesn't exist the program fails with a KeyError
, e.g.
$ python3 snake -t classi
Traceback (most recent call last):
File "/usr/lib/python3.6/runpy.py", line 193, in _run_module_as_main
"__main__", mod_spec)
File "/usr/lib/python3.6/runpy.py", line 85, in _run_code
exec(code, run_globals)
File "snake/__main__.py", line 26, in <module>
run()
File "snake/__main__.py", line 16, in run
stage.init()
File "snake/stage.py", line 43, in init
chosen_theme = themes.game_themes[parser.options.theme]
KeyError: 'classi'
This can be avoided by allowing only valid theme names in the CLI parser, e.g. via choices in argparse. Ideally, you fill in the choices
dynamically, directly from the themes module, e.g.
import argparse
from . import themes
parser = argparse.ArgumentParser(prog='snake')
parser.add_argument('-t', '--theme', type=str, choices=list(themes.game_themes))