Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Backwards-compatible input calls in Python

Tags:

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?

like image 718
Keith Hughitt Avatar asked May 03 '11 11:05

Keith Hughitt


People also ask

What is backwards compatible in Python?

The Python language does not provide backward compatibility.

Is Python 2 and 3 backwards compatible?

Python 3 is not backwards compatible with Python 2, so your code may need to be adapted. Please start migrating your existing your existing Python 2 code to Python 3. Python 2 series End Of Life is set to 1st of January 2020.

Is NumPy backwards compatible?

NumPy is also actively maintained and improved – and sometimes improvements require, or are made easier, by breaking backwards compatibility. Finally, there are trade-offs in stability for existing users vs. avoiding errors or having a better user experience for new users.

Why is Python not backward-compatible?

It does it on purpose, so the great features can be implemented even despite the fact Python 2. x code may not work correctly under Python 3. x. So, basically, Python 3.0 is not backward-compatible on purpose.


1 Answers

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.

like image 62
Sven Marnach Avatar answered Oct 14 '22 12:10

Sven Marnach