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

Eric Snow ericsnowcurrently at gmail.com
Thu Sep 22 21:14:44 CEST 2011

On Thu, Sep 22, 2011 at 12:49 PM, Carl Matthew Johnson
<cmjohnson.mailinglist at gmail.com> wrote:
> This reminds me that there was a proposal a few weeks back to be able to refer to the function one is in absolutely. Right now, you can't just slap an attribute onto f in a loop and then get it back at exec time, since the variable f will refer to the last f defined in the loop. But suppose we had some sort of "THIS_FUNCTION" magic variable…

Yeah, a "THIS_FUNCTION" in the function locals didn't go very far.  It
would be too easy to abuse it and the implementation doesn't fit well
into CPython (as far as I could see).  I have a patch in for adding
f_func to the frame object (you have to jump through the inspect
module to get to it).  However, that doesn't help so much for this.

> Then this would work:
> fs = []
> for i in range(10):
>    def f():
>        return THIS_FUNC.value
>    f.value = i
> [f() for f in fs]
> (Again, it has to be some sort of magical variable, since "return f.value" will refer to the 9 producing function at the end.)
> This could then be combined with a standard inject decorator.
>   @inject(i=i)
>    def f():
>        return THIS_FUNC.inject_values.i
> In cases where you're not in a loop or something, you could just write "f.values.i" instead of using the new magical variable.

Performance is another concern here.  The default argument hack is
pretty efficient compared to attribute lookups on the function object.


> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> http://mail.python.org/mailman/listinfo/python-ideas

More information about the Python-ideas mailing list