Skip to content Skip to sidebar Skip to footer

Handling Map Function In Python2 & Python3

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(

Solution 1:

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 both

python 3 vs python 2
  map    =   itertools.imap
  zip    =   itertools.izip
  filter =   itertools.ifilter
  range  =   xrange
  input  =   raw_input

so 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

my_input = input
try: 
    raw_input
except NameError: #we are in python 3
    my_input = lambda msj=None: eval(input(msj))

(or with your favorite way to check which version of python is in execution)

# code part in result reader
result = [ int(x) for x in my_input() ]
# consumer call
result_consumer(result)

that way your code do the same regardless of which version of python you run it.

But as jsbueno mentioned, eval and python2's input are dangerous so use the more secure raw_input or python3's input

try: 
    input = raw_input
except NameError: #we are in python 3
    pass

(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 split

# code part in result reader
result = [ int(x) for x in input().split(",") ]
# consumer call
result_consumer(result)

Solution 2:

If 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:

result = list(map(int, input()))

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 the list 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 the list only in Python 3 but that might be too tedious for you.


Solution 3:

I usually use my own version of map in this situations to escape any possible problem may occur and it's

def my_map(func,some_list):
    done = []
    for item in some_list:
        done.append( func(item) )
    return done

and my own version of input too

def getinput(text):
    import sys
    ver = sys.version[0]
    if ver=="3":
        return input(text)
    else:
        return raw_input(text)

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.


Post a Comment for "Handling Map Function In Python2 & Python3"