[Python-ideas] Before and after the colon in funciton defs.

Bruce Leban bruce at leapyear.org
Fri Sep 23 04:18:12 CEST 2011


On Thu, Sep 22, 2011 at 6:11 PM, Nick Coghlan <ncoghlan at gmail.com> wrote:

> On Fri, Sep 23, 2011 at 9:51 AM, Steven D'Aprano <steve at pearwood.info>
> wrote:
> > With decorator syntax, the scoping rules are obvious and straightforward:
> >
> > a = 10
> > @inject(b=a)
> > def foo():
> >    a = 20
> >    return b+a
>
> Please read the previous thread from June (linked earlier in this
> thread). Decorator syntax cannot work without deep magic, because the
> compiler *doesn't know* that injected names need to be given special
> treatment.
>
>
 Yes, you're right that this can't be done with today's decorators. That
doesn't mean it's impossible. Any of the other changes would also require
compiler changes. Instead of @inject being a standard decorator, imagine a
new kind of decorator that works as follows:

a = 10
$inject(b=a)
def foo()
    a = 20
    return b+a


where the effect of a $inject decorator is that it modifies the behavior of
the function as follows:

a = 10
_inject_ = inject_decorator(b=a)
def foo():
    locals().update(_inject_)
    a = 20
    return b + a


Yes, I know that update on locals() won't do the right thing but pretend it
does. I think the semantics of this are pretty clear and more obvious than
the suggested alternatives. Now what about these $-decorators? As defined
here, it's pretty specialized to this one operation. Let's imagine that we
define $-decorators to be a special class of decorators that are built into
Python. We use $-decorators for cases we would like users to think of as
decorators but that do some kind of magic that's beyond the capability of a
regular decorator. To the user the $ is a signal to the user that this
decorator is a bit more special than usual. Right now, there would only be
one $-decorator but it's available next time it's desired to add something
that just can't quite be a regular decorator.

A good objection to adding new things to the language is that they increase
the load on people trying to learn the language. If I see a syntax like:

def f() [i=i]: pass


I can't imagine how I would find out what that does. Search engines don't
readily allow searching on special characters. On the other hand, when I see
$inject, I go type "python $inject decorator" into my favorite search engine
and whether it ignores the $ or not, I'm fairly likely to get good results.
Whether the decorator-like syntax is spelled $inject, @@static or something
else, I think it's going to be much easier to figure out and remember what's
going on.

--- Bruce
Follow me: http://www.twitter.com/Vroo http://www.vroospeak.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20110922/c47c6d4f/attachment.html>


More information about the Python-ideas mailing list