Param decorator - can you suggest improvements
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Fri Jan 18 04:10:34 EST 2013
On Fri, 18 Jan 2013 03:38:08 +0000, Dan Sommers wrote:
> 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
There's not really any magic in that :-)
Better to use "if value is not sentinel" rather than != because the
caller might provide a custom object that compares equal to sentinel.
Also you should name it SENTINEL, or even _SENTINEL, to indicate that it
is (1) a constant, and (2) a private variable.
> It's not a function, nor a decorator, but it behaves like a function.
A callable, so-called because you can call it :-)
I believe that C++ calls it a "functor", not to be confused with what
Haskell calls a functor, which is completely different.
--
Steven
More information about the Python-list
mailing list