How to change string or number passed as argument?
python.list at tim.thechases.com
Sun Sep 20 04:08:58 CEST 2009
> I know that strings or numbers are immutable when they passed as
> arguments to functions. But there are cases that I may want to change
> them in a function and propagate the effects outside the function. I
> could wrap them in a class, which I feel a little bit tedious. I am
> wondering what is the common practice for this problem.
The most common way is to simply return the altered string if you
result = do_stuff(...)
some_string = mutate(some_string)
return result, some_string
result, value = my_func(value)
This gives the flexibility for the caller to decide whether they
want to allow the function to mutate the parameter or not.
You can also use a mutable argument:
lst = mutate(lst)
s = ["hello"]
result = my_func(s)
but this is horribly hackish.
In general, mutating arguments is frowned upon because it leads
to unexpected consequences. Just like I don't expect sin(x) or
cos(x) to go changing my input value, python functions should
More information about the Python-list