Case Statements

Steven D'Aprano steve at pearwood.info
Wed Mar 16 20:19:02 EDT 2016


On Thu, 17 Mar 2016 10:14 am, Chris Angelico wrote:

> On Thu, Mar 17, 2016 at 5:31 AM, Antoon Pardon
> <antoon.pardon at rece.vub.ac.be> wrote:
>> It can be yes. Look at decorators. They don't provide functionality
>> we wouldn't have without them.
> 
> Really? Okay, try implementing this without decorators:
 
[...]
> @monkeypatch
> class Foo:
[...]


I think Antoon is referring to decorator *syntax*, not the concept of
decorators in general. Decorator syntax is just syntactic sugar for:


class Foo:
    ...

Foo = monkeypatch(Foo)

which has been valid all the way back to Python 1.0.

Given first class functions and types, plus closures, I can't imagine how
you could fail to have decorators. Regardless of what monkeypatch actually
does internally, it takes a class as argument, and returns a new or
modified class. If you can create new classes on the fly, or modify them,
then you can implement decorator functionality, but without the convenience
of decorator syntax.

Indeed, Python started providing built-in decorators (such as classmethod
and staticmethod) as early as 2.2, but didn't gain the @ decorator syntax
until 2.4 for functions:

https://www.python.org/dev/peps/pep-0318/

and 2.6 for classes. The availability of a nice syntax to transform
functions and classes has, as Bruce Eckel predicted, transformed the Python
ecosystem, and decorators are now extensively used in libraries and
frameworks:

    The reason I think decorators will have such a big impact is
    because this little bit of syntax sugar changes the way you
    think about programming. Indeed, it brings the idea of 
    "applying code to other code" (i.e.: macros) into mainstream 
    thinking by formalizing it as a language construct.

http://www.artima.com/weblogs/viewpost.jsp?thread=240808



-- 
Steven




More information about the Python-list mailing list