How to change string or number passed as argument?

Tim Chase python.list at tim.thechases.com
Sat Sep 19 22:08:58 EDT 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 
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






More information about the Python-list mailing list