Skip to content
Permalink
Browse files

avoid evaluating arguments with choices in MagicParser

  • Loading branch information...
sdpython committed Mar 1, 2015
1 parent e336adf commit 6c42c1668d693033e83e82acdf81e1f124bddc99
Showing with 49 additions and 3 deletions.
  1. +49 −3 src/pyquickhelper/ipythonhelper/magic_parser.py
@@ -18,6 +18,48 @@ class MagicCommandParser (argparse.ArgumentParser):
.. versionadded:: 0.9
"""

def __init__(self, *l, **p):
"""
custom constructor, see `ArgumentParser <https://docs.python.org/3.4/library/argparse.html>`_
"""
argparse.ArgumentParser.__init__(self, *l, **p)
self._keep_args = {}

@staticmethod
def _private_get_name(*args):
"""
guesses the name of a parameter knowning the argument
given to @see me add_argument
"""
for i, a in enumerate(args):
if isinstance(a, str):
if a[0] != "-":
return a
elif a.startswith("--"):
return a[2:].replace("-", "_")
raise KeyError("unable to find parameter name in: " + str(args))

def add_argument(self, *args, **kwargs):
"""
overloads the methods, see `ArgumentParser <https://docs.python.org/3.4/library/argparse.html>`_
"""
super(argparse.ArgumentParser, self).add_argument(*args, **kwargs)
if args != ('-h', '--help'):
name = MagicCommandParser._private_get_name(*args)
self._keep_args[name] = (args, kwargs)

def has_choices(self, name):
"""
tells if a parameter has choises
@param name parameter name
@return boolean
"""
if name not in self._keep_args:
raise KeyError("unable to find parameter name: {0} in {1}".format(
name, list(self._keep_args.keys())))
return "choices" in self._keep_args[name][1]

def parse_cmd(self, line, context=None, fLOG=noLOG):
"""
split line using `shlex <https://docs.python.org/3.4/library/shlex.html>`_
@@ -34,9 +76,13 @@ def parse_cmd(self, line, context=None, fLOG=noLOG):
if context is not None:
up = {}
for k, v in res.__dict__.items():
ev = self.eval(v, context=context, fLOG=fLOG)
if ev != v:
up[k] = ev
if self.has_choices(k):
up[k] = v
else:
ev = self.eval(v, context=context, fLOG=fLOG)
if ev != v:
up[k] = ev

if len(up) > 0:
for k, v in up.items():
res.__dict__[k] = v

0 comments on commit 6c42c16

Please sign in to comment.
You can’t perform that action at this time.