[Python-Dev] [PEP] += on return of function call result
Andrew Koenig
ark@research.att.com
16 May 2003 08:07:23 -0400
ark> Why can't you do this?
ark> for t in range(5):
ark> for r in range(10):
ark> foo = log.setdefault(r,'')
ark> foo += "test %d\n" % t
Luke> after running this code,
Luke> log = {0: '', 1: '', 2:'', 3: '' ... 9: ''}
Luke> and foo equals "test 5".
Then that is what foo would be if you were able to write
log.setdefault(r,'') += "test %d\n" % t
as you had wished.
Luke> if, however, you do this:
Luke> for t in range(5):
Luke> for r in range(10):
Luke> foo = log.setdefault(r,[])
Luke> foo.append("test %d\n" % t)
Luke> then empirically i conclude that you DO end up with the
Luke> expected results (but is this true all of the time?)
I presume that is because you are now dealing with vectors instead
of strings. In that case, you could also have written
for t in range(5):
for r in range(10):
foo = log.setdefault(r,[])
foo += ["test %d]n" % t]
with the same effect.
Luke> the reason why your example, andrew, does not work, is
Luke> because '' is a string - a basic type to which a pointer is
Luke> NOT returned i presume that the foo += "test %d"... returns a
Luke> DIFFERENT result object such that the string in the dictionary
Luke> is DIFFERENT from the string result of foo being updated.
Well, yes. But that is what you would have gotten had you been allowed
to write
log.setdefault(r,"") += <whatever>
in the first place.
Luke> if that makes absolutely no sense whatsoever then think of it
Luke> being the difference between integers and pointers-to-integers
Luke> in c.
I think this analogy is pointless, as the only people who will understand
it are those who didn't need it in the first place :-)
Luke> can anyone tell me if there are any PARTICULAR circumstances where
Luke> foo = log.setdefault(r,[])
Luke> foo.append("test %d\n" % t)
Luke> will FAIL to work as expected?
It will fail if your expectations are incorrect or unrealistic.
Luke> andrew, sorry it took me so long to respond: i initially
Luke> thought that under all circumstances for all types of foo,
Luke> your example would work.
But it does! At least in the sense of the original query.
The original query was of the form
Why can't I write an expression like f(x) += y?
and my answer was, in effect,
If you could, it would have the same effect as if you had written
foo = f(x)
foo += y
and then used the value of foo.
Perhaps I'm missing something, but I don't think that anything you've said
contradicts this answer.
--
Andrew Koenig, ark@research.att.com, http://www.research.att.com/info/ark