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?
The Python language does not provide backward compatibility.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With