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
need it:
def my_func(some_string):
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:
def my_func(lst):
lst[0] = mutate(lst[0])
return do_stuff(...)
s = ["hello"]
result = my_func(s)
print s[0]
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
behave similarly.
-tkc
--
http://mail.python.org/mailman/listinfo/python-list