[Python-Dev] [PEP] += on return of function call result

Luke Kenneth Casson Leighton lkcl@samba-tng.org
Thu, 15 May 2003 21:44:18 +0000


On Wed, Apr 02, 2003 at 09:54:35AM -0500, Andrew Koenig wrote:
> Luke> example code:
> Luke> log = {}
> 
> Luke> 	for t in range(5):
> Luke> 		for r in range(10):
> Luke> 			log.setdefault(r, '') += "test %d\n" % t
> 
> Luke> pprint(log)
> 
> Luke> instead, as the above is not possible, the following must be used:
> 
> Luke> from operator import add
> 
> Luke>  ...
> Luke>       ...
> Luke> 	      ...
> 
> Luke> 			add(log.setdefault(r, ''), "test %d\n" % t)
> 
> Luke> ... ARGH!  just checked - NOPE!  add doesn't work.
> Luke> and there's no function "radd" or "__radd__" in the
> Luke> operator module.
> 
> Why can't you do this?
> 
>         for t in range(5):
>                 for r in range(10):
>                         foo = log.setdefault(r,'')
>                         foo += "test %d\n" % t
 
 after running this code,

 log = {0: '', 1: '', 2:'', 3: '' ... 9: ''}

 and foo equals "test 5".

 if, however, you do this:

         for t in range(5):
                 for r in range(10):
                         foo = log.setdefault(r,[])
                         foo.append("test %d\n" % t)
 
 then empirically i conclude that you DO end up with the
 expected results (but is this true all of the time?)

 the reason why your example, andrew, does not work, is
 because '' is a string - a basic type to which a pointer is
 NOT returned i presume that the foo += "test %d"... returns a
 DIFFERENT result object such that the string in the dictionary
 is DIFFERENT from the string result of foo being updated.

 if that makes absolutely no sense whatsoever then think of it
 being the difference between integers and pointers-to-integers
 in c.

 
 can anyone tell me if there are any PARTICULAR circumstances where

                         foo = log.setdefault(r,[])
                         foo.append("test %d\n" % t)

 will FAIL to work as expected?



 andrew, sorry it took me so long to respond: i initially
 thought that under all circumstances for all types of foo,
 your example would work.

 l.


-- 
-- 
expecting email to be received and understood is a bit like
picking up the telephone and immediately dialing without
checking for a dial-tone; speaking immediately without listening
for either an answer or ring-tone; hanging up immediately and
then expecting someone to call you (and to be able to call you).
--
every day, people send out email expecting it to be received
without being tampered with, read by other people, delayed or
simply - without prejudice but lots of incompetence - destroyed.
--
please therefore treat email more like you would a CB radio
to communicate across the world (via relaying stations):
ask and expect people to confirm receipt; send nothing that
you don't mind everyone in the world knowing about...