Journal Articles

CVu Journal Vol 31, #6 - January 2020 + Programming Topics
Browse in : All > Journals > CVu > 316 (11)
All > Topics > Programming (877)
Any of these categories - All of these categories

Note: when you create a new publication type, the articles module will automatically use the templates user-display-[publicationtype].xt and user-summary-[publicationtype].xt. If those templates do not exist when you try to preview or display a new article, you'll get this warning :-) Please place your own templates in themes/yourtheme/modules/articles . The templates will get the extension .xt there.

Title: Python has setdefault

Author: Bob Schmidt

Date: 06 January 2020 18:00:30 +00:00 or Mon, 06 January 2020 18:00:30 +00:00

Summary: Silas S. Brown shares a quick tip on Python.

Body: 

I learned Python in the days when Python 1.x was still around, incidentally as a result of reviewing Professional Linux Programming by Neil Matthew and Richard Stones, in CVu 13(2), April 2001. Python 2.0 had been released in October 2000 but it took a while for it to be fully integrated into GNU/Linux distributions etc. I did start using Python 2 whenever possible (not least because of its Unicode support) and made 2.0 my code's minimum requirement, but I only recently discovered in 2019 that all these years I’ve been using a certain Python 1.x idiom that 2.x has a single instruction for.

So, public service announcement (in case anybody else has been labouring under the same incomplete understanding all these years), if you often write code like this:

  if not myDict.has_key(k): myDict[k] = []
  myDict[k].append(s)

then you are still in the 1.x days on two counts: use of has_key (nowadays you can simply say if not k in myDict), and non-use of setdefault. In every version of Python from 2.0 onwards, the above is equivalent to:

  myDict.setdefault(k,[]).append(s)

and the only reason I can think of not to use this is if the constructor to the [] were so much overhead that you really don’t want to run it unless needed (which isn’t the case for the empty list, but might be the case for some user-defined type). Otherwise, setdefault away.

Silas S. Brown Silas is a partially-sighted Computer Science post-doc in Cambridge who currently works in part-time assistant tuition and part-time for Oracle. He has been an ACCU member since 1994.

Notes: 

More fields may be available via dynamicdata ..