Idiom gone, or did it really ever exist? () is ()

Russell E. Owen owen at astrono.junkwashington.emu
Wed Apr 18 12:53:49 EDT 2001


In article <mailman.987566424.29391.python-list at python.org>,
 "Mike C. Fletcher" <mcfletch at home.com> wrote:

>Over the years, I've occasionally used this idiom:
>
>NULLARGUMENT = ()
>
>def someFunctionOrMethod  (argument = NULLARGUMENT ):
>    if argument is NULLARGUMENT:
>        doSomething()
>    else:
>        doSomethingElse()
>
>That is, I was attempting to distinguish between a call where argument is
>passed a NULL tuple and a call where argument is passed nothing at all.
>When I was working on unit tests for my current piece of code, however, I
>discovered that this no longer works (Python 1.5.2).

I like your idiom and often use it, but you have a minor bug. You say 
you wish to distinguish between two cases:
- passing an empty tuple
- passing no argument at all
yet your default value for "argument" *is* an empty tuple, so your code 
cannot do the job. If you really want to do this job, pick any other 
default value, such as None or "".

A good choice of default depends on what values you expect. An example: 
in some of my GUI coding I want to distinguish between three cases:
- use a user-specified label
- use a default label
- no label

In that case I tend to code things as follows:

def myFunc(label=None):
    """A demonstration of default arguments
    Inputs:
    - label: if omitted, a default is supplied; if "" then no label
    """
    if label:
        print "label =:", label
    elif label is None:
        print "default label"
    else:
        print "no label"

-- Russell



More information about the Python-list mailing list