[Python-Dev] PEP 318 -- a couple use cases (original) (raw)
Edward Loper edloper at gradient.cis.upenn.edu
Thu Apr 1 11:56:39 EST 2004
- Previous message: [Python-Dev] PEP 318: Decorators last before colon
- Next message: [Python-Dev] PEP 318 -- a couple use cases
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
I saw both of the following use cases mentioned on the list, and they seemed interesting, so I went ahead and wrote up implementations:
def property_getter(func): """ A decorator that can be used to incrementally construct properties. For example, the following code constructs a property 'x' from an fget, an fset, and an fdel function:
>>> class A:
... def x(self) [property_getter]:
... return self.__x
... def x(self, val) [property_setter]:
... self.__x = val
... def x(self) [property_deleter]:
... del self.__x
In particular, this decorator checks if a property named
'func' is defined in the enclosing frame. If so, then it
updates that property's fget to be 'func'. If not, then
it creates a new property whose fget is 'func'. The
property's docstring is taken from the first decorated
property function to define a docstring.
"""
def generic(*type_signature): """ A decorator-generator that can be used to incrementally construct a generic function that delegates to individual functions based on the type signature of the arguments. For example, the following code defines a generic function that uses two different actual functions, depending on whether its argument is a string or an int:
>>> def f(x) [generic(int)]:
... print x, 'is an int'
>>> def f(x) [generic(str)]:
... print x, 'is a string'
In particular, the decorator returned by this function checks if a
Generic function-delegation object with the same name as the
decorated function is defined in the enclosing frame. If so, then
it registers the function with that generic object, under
'type_signature'. If not, then it creates a new Generic
function-delegation object, and registers the function.
"""
Full code is at <http://www.cis.upenn.edu/~edloper/pydecorators.html>.
But I still don't feel like I have a good handle on what "acceptable" uses of decorators are.. So, for each of these 2 use cases, is it... - an excellent example that should be included in the stdlib - perfectly acceptable, and belongs in the python cookbook - somewhat hackish, but ok under the right circumstances - an abhorition of nature
(If one of the first 3, then maybe they should be added to the pep?) Thanks for the feedback.
-Edward
- Previous message: [Python-Dev] PEP 318: Decorators last before colon
- Next message: [Python-Dev] PEP 318 -- a couple use cases
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]