Decorators (was: Re: I love assert)
Steven D'Aprano
steve+comp.lang.python at pearwood.info
Sat Nov 15 10:39:40 EST 2014
Richard Riehle wrote:
> Decorators are new in Python, so there are not a lot of people using them.
The principle of decorators themselves is as old as Python itself. You could
implement them as far back as Python 1.5, if not older:
[steve at ando ~]$ python1.5
Python 1.5.2 (#1, Aug 27 2012, 09:09:18) [GCC 4.1.2 20080704 (Red Hat
4.1.2-52)] on linux2
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def decorator(func):
... def inner(arg, func=func):
... return func(arg*2)
... return inner
...
>>> def f(x):
... return x + 1
...
>>> f = decorator(f)
>>> f(1)
3
>>> f(5)
11
The first built-in decorators (classmethod, staticmethod and property) were
added in Python 2.2. Decorator syntax using @ was added in 2.4.
https://docs.python.org/2/whatsnew/2.4.html#pep-318-decorators-for-functions-and-methods
So decorators have been available for a very long time.
> From my experience with other languages, especially Ada and Eiffel, I
> enjoy the benefit of assertions (as pre-conditions and post-conditions and
> invariants) at the specification level (not embedded in the code), so
> decorators are closer to my other experience. They bring me closer to
> the Design by Contract model of Ada and Eiffel. That is why I was so
> pleased to see them added to Python.
Way back in Python 1.5, Guido van Rossum wrote an essay describing a way to
get Eiffel-like checks for pre-conditions and post-conditions:
https://www.python.org/doc/essays/metaclasses/
(Alas, the link to Eiffel.py is currently broken. But you can read the rest
of the essay.)
> It is true, however, that they are not immediately intutive in Python, but
> once understood, they are handy IMHO for improving code reliability.
> Perhaps I was spoiled by having this capability in some other languages.
--
Steven
More information about the Python-list
mailing list