Skip to content Skip to sidebar Skip to footer

Function To Change Values Of Variables

I am facing following problem; Let's say I have following: a = 0 def something(variable): variable = variable + 1 something(a) print(a) The output is 0 instead of 1.. and i

Solution 1:

Variables enter functions as parameters, and leave them as return values:

defsomething(variable)
    variable += 1return variable

a = 0
a = something(a)
print(a)

Solution 2:

Python doesn't have the conceptual equivalent of void func(int * a) or void func(int & a) that can be used in C-likes as an 'in/out' parameter. While method arguments in python are pass-by-reference, all of the numeric types are immutable, and so the only way to alter a numeric variable's value is via an assignment, which creates a new reference for that name rather than altering the existing value.

The simplest way to alter the value of a from your example is of course to assign the return to the input:

a = do_something(a)

The potential gotcha with this is that anything that aliased a will not reflect the change, I.E.

a = 0
b = a
a = do_something(a)
print(a)
>>> 1print(b)
>>> 0

To get equivalent behavior to int * a, you have to wrap the numeric value in a simple mutable data structure, like a list/dict, or place in in a class. Examples below:

classmutable_number(object):
    def__init__(value):
        self._value = value

    @propertydefvalue(self):
        return self._value

    @value.setterdefvalue(self, value):
        self._value = value

list_a  = [0]
dict_a  = {'a':0}
class_a = mutable_number(0)

defdo_something_l(lst):
    lst[0] += 1defdo_something_d(dct):
    dct['a'] += 1defdo_something_c(cls):
    cls.value += 1

do_something_l(list_a)
do_something_d(dict_a)
do_something_c(class_a)

print(list_a[0])
print(dict_a['a'])
print(class_a.value)
>>> 1>>> 1>>> 1

These forms all will work properly with aliasing, so if I had done

class_a = mutable_number(0)
class_b = class_a

And then at the end

print(class_b.value)
>>> 1

You get the expected output.

The other thing to remember is that python supports simple syntax for multiple returns via a tuple:

return a,b,c

And Exceptions are considered good programming style, so many of the use-cases for 'in/out' arguments in C-likes aren't really required (E.X.: Alter input parameter, return error code, or alter multiple input arguments in a void)

Post a Comment for "Function To Change Values Of Variables"