Is it explicitly specified?

Arnaud Delobelle arnodel at googlemail.com
Sun Feb 3 18:49:01 EST 2008


On Feb 3, 11:06 pm, "Terry Reedy" <tjre... at udel.edu> wrote:


> If you have multiple optional keywords with default behaviors when they are
> not specified, the usually mechanism is the **keywords mechanism.  If you
> have just one, that may seem like overkill and some people prefer the
> pseudo-default or sentinal value approach given by Arnaud.  The only change
> I would make from his post is to add at least an underscore to the sentinal
> name to indicate that it is private to the module and not for use of
> importers (and excluded from 'import *').

Yes, or you can even be more radical and use this construct which
leverages the little known fact that 'apply', far from being a mere
deprecated built-in function, is in fact a powerful decorator that
reduces namespace pollution!

@apply
def func(nokey=object()):
    def the_real_func(key=nokey):
        if key is nokey:
            print "no key given"
        else:
            print "key given"
    return the_real_func

>>> func(1)
key given
>>> func()
no key given
>>> func(key=2)
key given

Note that 'apply' has many uses:

Say I have an expensive function f and I want to find y=f(x)*(1+f(x))

Instead of having to pollute my namespace with a temp value:
temp = f(x)
y = temp*(1+temp)

I can use the very pythonic 'apply' decorator:
@apply
def y(z=f(x)): return z*(1+z)

Mmh.  Maybe I should patent it, I've never seen it before...

--
Arnaud

PS: this is not a serious suggestion :)




More information about the Python-list mailing list