Search code examples
pythonuser-inputpython-2.x

Is it ever useful to use Python's input over raw_input?


I currently teach first year university students python, and I was surprised to learn that the seemingly innocuous input function, that some of my students had decided to use (and were confused by the odd behaviour), was hiding a call to eval behind it.

So my question is, why does the input function call eval, and what would this ever be useful for that it wouldn't be safer to do with raw_input? I understand that this has been changed in Python 3, but it seems like an unusual design decision in the first place.

Python 2.x input function documentation


Solution

  • Is it ever useful to use Python 2's input over raw_input?

    No.


    input() evaluates the code the user gives it. It puts the full power of Python in the hands of the user. With generator expressions/list comprehensions, __import__, and the if/else operators, literally anything Python can do can be achieved with a single expression. Malicious users can use input() to remove files (__import__('os').remove('precious_file')), monkeypatch the rest of the program (setattr(__import__('__main__'), 'function', lambda:42)), ... anything.

    A normal user won't need to use all the advanced functionality. If you don't need expressions, use ast.literal_eval(raw_input()) – the literal_eval function is safe.

    If you're writing for advanced users, give them a better way to input code. Plugins, user modules, etc. – something with the full Python syntax, not just the functionality.

    If you're absolutely sure you know what you're doing, say eval(raw_input()). The eval screams "I'm dangerous!" to the trained eye. But, odds are you won't ever need this.


    input() was one of the old design mistakes that Python 3 is solving.