The difference between input and raw_input in Python

One of the first things that people notice when they ditch Python 2 and start coding in Python 3 – apart from the fact that print  is now a function – is that the raw_input  function has disappeared. So this Python 2 code:

must be converted to this in Python 3:

The change comes because the Python developers realized that they had made a dangerous mistake back in the early days. If you recall, the Python 2 version of the input  function used to be equivalent to this:

This allowed you to easily write programs that take input from the user and evaluate it as an int or a float or whatever type it is. For example:

raw_input, on the other hand, returned strings:

In Python 3, input  behaves like raw_input  in Python2, and the raw_input  function does not exist, so you have to do something like this (assuming you want to accept integer values):

Effectively, in the Python 2 version of the input  function, the string read from the prompt was evaled. To understand the danger of eval , you should take a look at this article by Ned Batchelder.

Automatically evaling whatever anybody decides to type at the prompt maybe makes things a little easier in a teaching context, because students don’t have to learn to convert strings to their intended types, but it also leaves the program open to executing arbitrary code that the user types in, revealing private information about your system or damaging it in some way.

Take this for example:

That will print the current working directory of your program.

Or if someone really wants to screw things up for you, they could just execute a recursive delete of your home directory. DO NOT RUN THIS CODE:

There is no need for Python to contain such footguns, regardless of their dubious teaching value.

To get the old behaviour of input  (which I hope I have convinced you that you do not want), replace your calls to it with eval(input()) . In fact, that is exactly what the automatic porting tool 2to3  does.

Tags: No tags

Comments are closed.