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

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


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.

Leave a Comment