Checking default arguments

Ben Finney bignose+hates-spam at benfinney.id.au
Sat Feb 3 00:18:39 EST 2007


igorr at ifi.uio.no (Igor V. Rafienko) writes:

> I was wondering whether it was possible to find out which parameter
> value is being used: the default argument or the user-supplied one.
> That is:
>
> def foo(x, y="bar"):
>     # how to figure out whether the value of y is 
>     # the default argument, or user-supplied?

If it doesn't make a difference, use "bar".

If it *does* make a difference, use a unique object:

===== wombat.py =====
    Y_DEFAULT = object()

    def foo(x, y=Y_DEFAULT):
        if y is Y_DEFAULT:
            # no value for y was supplied
        else:
            # y value was specified by caller
=====

===== fnord.py =====

    import wombat

    foo("spam")    # 'y' argument gets unique default object
    foo("spam", "eggs")    # 'y' argument is supplied by caller
=====

By using a unique object, and comparing on "is", you make it clear
that this is never going to match any other value that is created
elsewhere in the program.

Of course, the "consenting adults" maxim applies: if a perverse user
wnats to call 'foo("spam", wombat.Y_DEFAULT)' this doesn't prevent it,
but then they've explicitly asked for it.

-- 
 \       "A lot of people are afraid of heights. Not me, I'm afraid of |
  `\                                        widths."  -- Steven Wright |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list