Skip to content
This repository has been archived by the owner on Jan 13, 2024. It is now read-only.

Commit

Permalink
avoid evaluating arguments with choices in MagicParser
Browse files Browse the repository at this point in the history
  • Loading branch information
sdpython committed Mar 1, 2015
1 parent e336adf commit 6c42c16
Showing 1 changed file with 49 additions and 3 deletions.
52 changes: 49 additions & 3 deletions src/pyquickhelper/ipythonhelper/magic_parser.py
Expand Up @@ -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>`_
Expand All @@ -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
Expand Down

0 comments on commit 6c42c16

Please sign in to comment.