27

I was wondering if anyone has suggestions for writing a backwards-compatible input() call for retrieving a filepath?

In Python 2.x, raw_input worked fine for input like /path/to/file. Using input works fine in this case for 3.x, but complains in 2.x because of the eval behavior.

One solution is to check the version of Python and, based on the version, map either input or raw_input to a new function:

if sys.version_info[0] >= 3:
    get_input = input
else:
    get_input = raw_input

I'm sure there is a better way to do this though. Anyone have any suggestions?

1
  • 4
    If you are writing code that is to run under Python 2 and Python 3 without using 2to3, you want this: pypi.python.org/pypi/six It has already solved many things like this for you. It also works as a good example on how to solve these kinds of problems (although it does in fact not do it for input()). Other ways of doing it is using 2to3. See python3porting.com/strategies.html May 3, 2011 at 12:25

4 Answers 4

36

Since the Python 2.x version of input() is essentially useless, you can simply overwrite it by raw_input:

try:
    input = raw_input
except NameError:
    pass

In general, I would not try to aim at code that works with both, Python 2.x and 3.x, but rather write your code in a way that it works on 2.x and you get a working 3.x version by using the 2to3 script.

16

This code is taught in many Python education and training programs now.

Usually taught together:

from __future__ import print_function
if hasattr(__builtins__, 'raw_input'):
    input = raw_input

First line: imports the Python 3.x print() function into Python 2.7 so print() behaves the same under both versions of Python. If this breaks your code due to older print "some content" calls, you can leave this line off.

Second and third lines: sets Python 2.7 raw_input() to input() so input() can be used under both versions of Python without problems. This can be used all by itself if this is the only compatibility fix you wish to include in your code.

There are more from __future__ imports available on the Python.org site for other language compatibility issues. There is also a library called "six" that can be looked up for compatibility solutions when dealing with other issues.

1

The way you are handling it is just fine. There are probably more similar ways using the sys module, but just in keep in mind that if you are program is doing something more than trivial with strings and files, it is better to have two versions of your program instead of having a backwards compatible python3 program.

1

You could import the function:

from builtins import input

Unfortunately though this method requires an external dependency via pip install future

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.