Search code examples
pythonconfigparser

Any downside to overriding ConfigParser get() method to include an eval?


I'm creating a subclass of ConfigParser that is easier for me to use throughout my project:

class MyConfiguration(ConfigParser.ConfigParser):

    def __init__(self, filename):
        ConfigParser.ConfigParser.__init__(self)
        self.readfp(open(filename))

    def get(self, section, option):
        return eval(ConfigParser.ConfigParser.get(self, section, option))

Question: are there any downsides (security, unintended consequences) to overriding the get() method with one that includes eval?

I'd rather bake the eval into the MyConfiguration class because I want to use Python data types (tuples, etc.) in my config files but I don't want to deal with evals all over my project code.


Solution

  • If your only interest in eval is literal values as you seem to indicate, then you can use ast.literal_eval

    This will read tuple literals, list literals and others and is safe to use because it is selective about what it will accept.

    >>> import ast
    >>> a = ast.literal_eval('(1, 2, 3)')
    >>> a
    (1, 2, 3)
    >>> b = ast.literal_eval('__import__("evil")')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
      File "/usr/lib/python2.6/ast.py", line 68, in literal_eval
        return _convert(node_or_string)
      File "/usr/lib/python2.6/ast.py", line 67, in _convert
        raise ValueError('malformed string')
    ValueError: malformed string
    

    Use cases like this are exactly what this function is intended for.