Case Statements

Chris Angelico rosuav at gmail.com
Wed Mar 16 20:31:32 EDT 2016


On Thu, Mar 17, 2016 at 11:19 AM, Steven D'Aprano <steve at pearwood.info> wrote:
> 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.
>

Yes... in theory. But try rewriting my example to avoid decorator
syntax. It won't work, because of this line:

    orig = globals()[cls.__name__]

It depends on the decorator being run before the name actually gets
bound - which means the previous class is available to the decorator.
You can't do that without decorator syntax, or messing around with
multiple names.

It works under PyPy3, CPython 3, and MicroPython; running it under a
Py2-compatible interpreter has issues with bound methods, but other
than that, it works on CPython 2, Jython, and PyPy2. Feel free to try
it under other interpreters to see if any of them actually implement
decorators as per their description.

ChrisA



More information about the Python-list mailing list