Is this unpythonic?

Gregory Ewing greg.ewing at canterbury.ac.nz
Sat May 9 03:47:16 EDT 2015


Frank Millman wrote:
> There are two operations I might perform on the dictionary -
> 
> 1. iterate over the keys and retrieve the values
> 
> 2: use 'in' to test if a given string exists as a key
> 
> Both of these operations will work on a tuple and give the desired result, 
> so it is a very valid workaround.

Although if I were reviewing a function like that,
it would probably make me pause for a moment or two
to consider why a tuple was being used as a value
for a parameter that is ostensibly supposed to be
a dict, and convince myself that it was okay.

The absolutely clearest way to write it would
probably be

    def f(things = None):
       "things is a mapping of stuff to be operated on"
       if things:
          for key in things:
             value = things[key]
             ...

A default value of None is a well-established idiom
for "this parameter is optional", and "if x:" is
idiomatic for "if I've been given an x", so writing it
that way has the best chance of passing the "pretty much
what you expect" test for good code. :-)

-- 
Greg



More information about the Python-list mailing list