Repository: ipython/ipython

Issue:
commandline parser can't handle --something="all"
It seems that parsing `all` will convert it to the `all()` function and an error is shown:

``` python
knitpy_aliases.update({
    'to' : 'KnitpyApp.export_format',
    [...]
})

class KnitpyApp(BaseIPythonApplication):
    # '--to' ends up here
    export_format = CaselessStrEnum(VALID_OUTPUT_FORMATS+["all"],
        default_value=DEFAULT_OUTPUT_FORMAT,
        config=True,
        help="""The export format to be used."""
    )
```

and then when I call it:

```
$ knitpy --to="all" example\hello.pymd # or `--to=all`
[...]
[KnitpyApp] CRITICAL | The 'export_format' trait of a KnitpyApp instance must be
 any of [u'pdf', u'docx', u'html', u'all'] or None, but a value of <built-in fun
ction all> <type 'builtin_function_or_method'> was specified.
```



Discussion:
The problem is in `IPython.config.loader.CommandLineConfigLoader`:

```
    def _exec_config_str(self, lhs, rhs):
        """execute self.config.<lhs> = <rhs>

        * expands ~ with expanduser
        * tries to assign with raw eval, otherwise assigns with just the string,
          allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent.  *Not*
          equivalent are `--C.a=4` and `--C.a='4'`.
        """
        rhs = os.path.expanduser(rhs)
        try:
            # Try to see if regular Python syntax will work. This
            # won't handle strings as the quote marks are removed
            # by the system shell.
            value = eval(rhs) # Here we get the all function...
        except (NameError, SyntaxError):
            # This case happens if the rhs is a string.
            value = rhs

        exec(u'self.config.%s = value' % lhs)
```

This is called from `KVArgParseConfigLoader._convert_to_config()`, which is called from `ArgParseConfigLoader.load_config()`, which is called from `Application.parse_command_line()`

My workaround is currently this:

```
class KnitpyApp(BaseIPythonApplication):
    [...]
    export_format = CaselessStrEnum(VALID_OUTPUT_FORMATS+["all"],
        default_value=DEFAULT_OUTPUT_FORMAT,
        config=True,
        help="""The export format to be used."""
    )
    # This is a workaround for https://github.com/ipython/ipython/issues/8025
    # a value of "all" is converted to the function `all` during commandline parsing, which 
    # raises if that is set as `export_format`. So on config change, first change it back and 
    # then call the original _config_changed(), which puts the config values to the traits
    def _config_changed(self, name, old, new):
        if get_by_name(new, "KnitpyApp.export_format", na=None) is all:
            new.KnitpyApp.export_format = "all"
        super(KnitpyApp, self)._config_changed(name, old, new)
```


Resolving patch:
diff --git a/IPython/config/loader.py b/IPython/config/loader.py
--- a/IPython/config/loader.py
+++ b/IPython/config/loader.py
@@ -11,6 +11,7 @@
 import re
 import sys
 import json
+from ast import literal_eval
 
 from IPython.utils.path import filefind, get_ipython_dir
 from IPython.utils import py3compat
@@ -487,7 +488,7 @@ def _exec_config_str(self, lhs, rhs):
         """execute self.config.<lhs> = <rhs>
         
         * expands ~ with expanduser
-        * tries to assign with raw eval, otherwise assigns with just the string,
+        * tries to assign with literal_eval, otherwise assigns with just the string,
           allowing `--C.a=foobar` and `--C.a="foobar"` to be equivalent.  *Not*
           equivalent are `--C.a=4` and `--C.a='4'`.
         """
@@ -496,8 +497,8 @@ def _exec_config_str(self, lhs, rhs):
             # Try to see if regular Python syntax will work. This
             # won't handle strings as the quote marks are removed
             # by the system shell.
-            value = eval(rhs)
-        except (NameError, SyntaxError):
+            value = literal_eval(rhs)
+        except (NameError, SyntaxError, ValueError):
             # This case happens if the rhs is a string.
             value = rhs
 


Test patch:
diff --git a/IPython/config/tests/test_loader.py b/IPython/config/tests/test_loader.py
--- a/IPython/config/tests/test_loader.py
+++ b/IPython/config/tests/test_loader.py
@@ -33,7 +33,7 @@
 c.a=10
 c.b=20
 c.Foo.Bar.value=10
-c.Foo.Bam.value=list(range(10))  # list() is just so it's the same on Python 3
+c.Foo.Bam.value=list(range(10))
 c.D.C.value='hi there'
 """
 
@@ -188,14 +188,23 @@ def test_argv(self):
 class TestKeyValueCL(TestCase):
     klass = KeyValueConfigLoader
 
+    def test_eval(self):
+        cl = self.klass(log=log)
+        config = cl.load_config('--Class.str_trait=all --Class.int_trait=5 --Class.list_trait=["hello",5]'.split())
+        self.assertEqual(config.Class.str_trait, 'all')
+        self.assertEqual(config.Class.int_trait, 5)
+        self.assertEqual(config.Class.list_trait, ["hello", 5])
+
     def test_basic(self):
         cl = self.klass(log=log)
-        argv = ['--'+s.strip('c.') for s in pyfile.split('\n')[2:-1]]
+        argv = [ '--' + s[2:] for s in pyfile.split('\n') if s.startswith('c.') ]
+        print(argv)
         config = cl.load_config(argv)
         self.assertEqual(config.a, 10)
         self.assertEqual(config.b, 20)
         self.assertEqual(config.Foo.Bar.value, 10)
-        self.assertEqual(config.Foo.Bam.value, list(range(10)))
+        # non-literal expressions are not evaluated
+        self.assertEqual(config.Foo.Bam.value, 'list(range(10))')
         self.assertEqual(config.D.C.value, 'hi there')
     
     def test_expanduser(self):