Param decorator - can you suggest improvements

Dan Sommers dan at tombstonezero.net
Thu Jan 17 22:38:08 EST 2013


On Thu, 17 Jan 2013 15:21:08 +0000, Steven D'Aprano wrote:

> 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:
> [...]

This, or something like this, is very old:

sentinel = object()
class Magic:
    def __init__(self, value):
        self.value = value
    def __call__(self, value=sentinel):
        if value != sentinel:
            self.value = value
        return self.value

It's not a function, nor a decorator, but it behaves like a function.  
I'm pretty sure that it's from Alex Martelli, and ended up as an 
ActiveState recipe at some point, but I can't find it now (I didn't look 
very hard).  It may have been called Magic, or it may have been called 
Pocket.  And the sentinel may have been None, but then you can't set the 
value to None (at least not through the apparent API).

Dan



More information about the Python-list mailing list