[Tutor] Please comment my -first- script

Kent Johnson kent_johnson at skillsoft.com
Thu Aug 19 16:12:01 CEST 2004


At 09:24 AM 8/19/2004 +0200, Bernard Lebel wrote:
> > - You should put the setdefault() call inside the try block for
>ValueError,
> > because if you get the exception then sName and sPad haven't been set
>(they
> > will have stale values in them probably):
> >                                  try:
> >                                          sName, sPad, sExt =
>oFile.split( '.' )
> >                                          aNames.setdefault( sName, []
> > ).append( sPad )
> >                                  except ValueError:
> >                                          pass
>
>Well yes, I didn't have the choice to do that, because otherwise the script
>fails.

That's troubling. How does it fail?

> > By the way do you understand what the setdefault call is doing? This is
>one
> > of the coolest Python idioms I know. (I'll let you figure it out :-)
>
>Hum not really. I have looked in the documentation but could not find much
>details about that. Can you elaborate if you don't mind?

OK, let's deconstruct this:
aNames.setdefault( sName, [] ).append( sPad )

First, look at
aValue = aNames.setdefault(sName, [])

This is roughly equivalent to
try:
   aValue = aNames[sName]
except KeyError:
   aValue = []
   aNames[sName] = aValue

This tries to get the dict value corresponding to sName. If it exists, 
that's it. If it doesn't exist, it creates a new list, assigns it to 
aValue, and _also_ stores a reference to the list in aNames.

Now aValue and aNames[sName] hold references to the same list. Since lists 
are mutable, appending to the list changes the list held by aNames.

Doing it all in one statement just eliminates the named variable aValue, 
the effect is the same.

Kent 



More information about the Tutor mailing list