Recently i came across a question & confused with a possible solution, code part is
// code part in result reader
result = map(int, input())
// consumer call
result_consumer(result)
its not about how do they work, the problem is when you are running in python2
it will raise an exception, on result fetching part, so result reader can handle the exception, but incase of python3
a map object
is returned, so only consumer will be able to handle exception.
is there any solution keeping map
function & handle the exception in python2
& python3
python3
>>> d = map(int, input())
1,2,3,a
>>> d
<map object at 0x7f70b11ee518>
>>>
python2
>>> d = map(int, input())
1,2,3,'a'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: 'a'
>>>
the behavior of
map
is not the only difference between python2 and python3,input
is also difference, you need to keep in mind the basic differences between the two to make code compatible for bothso to make code for both, you can use alternatives like list comprehension that work the same for both, and for those that don't have easy alternatives, you can make new functions and/or use conditional renames, like for example
(or with your favorite way to check which version of python is in execution)
that way your code do the same regardless of which version of python you run it.
But as jsbueno mentioned,
eval
and python2'sinput
are dangerous so use the more secureraw_input
or python3'sinput
(or with your favorite way to check which version of python is in execution)
then if your plan is to provide your input as
1,2,3
add an appropriate splitIf you always need the exception to occur at the same place you can always force the map object to yield its results by wrapping it in a
list
call:If an error occurs in Python 2 it will be during the call to
map
while, in Python 3, the error is going to surface during thelist
call.The slight downside is that in the case of Python 2 you'll create a new list. To avoid this you could alternatively branch based on
sys.version
and use thelist
only in Python 3 but that might be too tedious for you.I usually use my own version of map in this situations to escape any possible problem may occur and it's
and my own version of input too
if you are working on a big project add them to a python file and import them any time you need like what I do.