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

Jack Diederich jackdied at gmail.com
Sat May 21 01:10:01 CEST 2011


On Fri, May 20, 2011 at 11:03 AM, Nick Coghlan <ncoghlan at gmail.com> wrote:
> I share Steve's puzzlement as the intended use case.
>
> To get value from the magic empty immutable list, you will have to
> explicitly test that calling your function with the default value does
> the right thing.
>
> But if you're writing an explicit test, having that test call the
> function *twice* to confirm correct use of the 'is None' idiom will
> work just as well.
>
> There are limits to how much we can help people that don't test their code.

The use case isn't very fancy, it's to have a generic empty iterable
as a place holder in function defs instead of doing the "if x is None"
dance.  Unit tests make using a real empty iterable less likely to
trigger bad behavior, but because the behavior of real empty iterables
in function defs is tricky and non-intuitive, unit tests for some of
those functions would need some extra boilerplate.

That might not be a bad tradeoff compared to adding extra "if x is
None" checks for each optional arg to a function.

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 = {}

    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)

-Jack



More information about the Python-ideas mailing list