Passing a string argument by reference

Irmen de Jong irmen at -NOSPAM-REMOVETHIS-xs4all.nl
Sun Aug 3 22:37:33 CEST 2003


Andrew Chalk wrote:
> I am a raw beginner to Python. I just read in "Learning Python" that
> assigning to a string argument inside a function does not change the string
> in the caller. I want an assignment in the function to alter the passed
> string in the caller. Is there any way to do this?

No. Strings are immutable. However, there is a better solution to do what
you want: just return the new value as a result of the function, and
let the caller process this further.

Example:

def addBarToString(variable):
     return variable+"bar"

called with:

variable="foo"
variable=addBarToString(variable)
print variable

results in >>foobar<< to be printed.


> For example
> 
> def SafeAdd(self, Variable, Value):
>     if self.form.has_key( Value ):
>     Variable = self.form[Value].value
> 
> Called with:
> 
> self.SafeAdd(self.txtCIF, 'txtCIF')
> 
> self.CIF is not changed on return from the function. How do I modify this so
> that it is?

I understand that you want to assign self.txtCIF  (not self.CIF as you
wrote) the value of self.form['txtCIF'], but only if that value
occurs in self.form?

There is a much easier way to do this. I suspect that self.form is
a dictionary (or a dict-like object).

Just use:

   self.txtCIF = self.form.get('txtCIF', self.txtCIF)

The second argument to the get method is the default value that is
returned if the required key is not present in the dict.
In this case, it returns the 'old' value of self.txtCIF, so in effect,
self.txtCIF will be unchanged if 'txtCIF' does not occur in self.form.
Also see http://www.python.org/doc/current/lib/typesmapping.html

Hope this helps!
--Irmen de Jong





More information about the Python-list mailing list