[Python-ideas] function defaults and an empty() builtin

Terry Reedy tjreedy at udel.edu
Sat May 21 23:48:55 CEST 2011


On 5/20/2011 7:10 PM, Jack Diederich wrote:

> The use case isn't very fancy, it's to have a generic empty iterable

If () and frozenset() are not generic enough for *you*, try this:

def empty():
     raise StopIteration
     yield
emp = empty()
for i in emp: print('something')
for i in emp: print('something')
# prints nothing, both times.

Actually, iter(()), iter([]), iter({}) behave the same when iterated.

> as a place holder in function defs instead of doing the "if x is None"

That idiom is for a completely differert use case:
when one wants a new empty *mutable* on every call, that will be filled 
with values and, typically, returned.

> FYI, here is the code that triggered the query.  The "if None" check
> is mostly habit with a small dose of pedagogical reinforcement for
> other devs that would read it.
>
> def query_sphinx(search_text, include=None, exclude=None):
>      if include is None:
>          include =  {}
>      if exclude is None:
>          exclude = {}

Since you are not mutating include and exclude, there is no point to 
this noise. I fact, I consider it wrong because it actually *misleads* 
other devs who would expect something put into each of them and 
returned. The proper way to write this is

def query_sphinx(search_text, include={}, exclude={}):

which documents that the parameters should be dicts (or similar) and 
that they are read only. You version implies that it would be ok to 
write to them, which is wrong.

>
>      query = sphinxapi.client()
>
>      for field, values in include.items():
>          query.SetFilter(field, values)
>      for field, values in exclude.items():
>          query.SetFilter(field, values, exclude=True)
>
>      return query.query(search_text)

-- 
Terry Jan Reedy




More information about the Python-ideas mailing list