Skip to content Skip to sidebar Skip to footer

Python Inplace Update Of Function Arguments?

I am trying to create a function that updates arguments inplace (mostly for curiosity's sake): def inplaceUpdate(f, inputs): for i in inputs: i = f(i) I have three inp

Solution 1:

In Python, integers are immutables. There's an on-topic question here.

The idea is that you cannot change the value of the references x, y and z. That means that if you do:

x = 2
y = 3
z = 4
some_func([x, y, z])

There's no way that some_funcchanges the value of the variables x, y, and z.

However, lists are mutable, and you could do:

defsome_func(l):
    l[:] = [i*2for i in l]

l = [2, 3, 4]
some_func(l)

print l  # the array has changed

And this would indeed change the list. This is because the operation l[:]=... assigns to the containment of the list, instead of reassigning the reference --that would be l=....

Solution 2:

Seems, what you whant is to map a list. There is beautiful builtin function map for that

# Declare lambda somewheref = lambda i: i**2# Map your inputsinput = [1, 2, 3]
result = map(f, input)

Solution 3:

You can also use list comprehensions to achieve this. Its more pythonic than map, but does essentially the same thing.

input = [1, 2, 3]
ls = [x**2 for x in input]

Solution 4:

There is no way to modify the values of the variables of the calling function with out using ugly hackery. If you saved a reference to the mutable list you created in [x,y,z], the inplaceUpdate function could modify it.

To accomplish this task using ugly hacks:

definPlaceUpdate(inputs):
   frame = sys._getframe(1)
   forinputin inputs:
       i = f(input)
       for k,v in frame.f_locals.iteritems():
           if v == input:
               frame.f_locals[k] = i
               breakelse:
          for k,v in frame.f_globals.iteritems():
              if v == input:
                 frame.f_globals[k] = i
                 break

Post a Comment for "Python Inplace Update Of Function Arguments?"