Param decorator - can you suggest improvements

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Jan 17 10:21:08 EST 2013


On Thu, 17 Jan 2013 06:35:29 -0800, Mark Carter wrote:

> I thought it would be interesting to try to implement Scheme SRFI 39
> (Parameter objects) in Python.
> 
> The idea is that you define a function that returns a default value. If
> you call that function with no arguments, it returns the current
> default. If you call it with an argument, it resets the default to the
> value passed in. Here's a working implementation:
[...]
> Can anyone suggest a better implementation?

I don't like the decorator version, because it requires creating a do-
nothing function that just gets thrown away. He's my version, a factory 
function that takes two arguments, the default value and an optional 
function name, and returns a Param function:

def param(default, name=None):
    SENTINEL = object()
    default = [default]
    def param(arg=SENTINEL):
        if arg is SENTINEL:
            return default[0]
        else:
            default[0] = arg
            return arg
    if name is not None:
        param.__name__ = name
    return param


In Python 3, it's even nicer, although no shorter:

def param(default, name=None):
    SENTINEL = object()
    def param(arg=SENTINEL):
        nonlocal default
        if arg is SENTINEL:
            return default
        else:
            default = arg
            return arg
    if name is not None:
        param.__name__ = name
    return param



-- 
Steven



More information about the Python-list mailing list