views:

51

answers:

2

In 2.6, if I needed to accept input that allowed a percent sign (such as "foo % bar"), I used raw_input() which worked as expected.

In 3.0, input() accomplishes that same (with raw_input() having left the building).

As an exercise, I'm hoping that I can have a backward-compatible version that will work with both 2.6 and 3.0.

When I use input() in 2.6 and enter "foo % bar", the following error is returned:

  File "<string>", line 1, in <module>
NameError: name "foo" is not defined

...which is expected.

Anyway to to accomplish acceptance of input containing a percent sign that works in both 2.6 and 3.0?

Thx.

+2  A: 

You can use sys.version_info to detect which version of Python is running.

import sys
if sys.version_info[0] == 2:
    input = raw_input
# Now you can use
input()

Alternatively, if you don't want to override Python 2.X's builtin input function, you can write

import sys
if sys.version_info[0] == 2:
    my_input = raw_input
else:
    my_input = input
# Now you can use
my_input()

Although, even in my first code sample, the original builtin input is always available as __builtins__.input.

David Zaslavsky
I went with the first option mentioned -- least instrusive. Many thanks!
bug11
+2  A: 

Although not an elegant (and rather ugly) solution, I would just do something like this:

try:
    input = raw_input
except:
    pass
Gabe