[Python-ideas] Access to function objects

Steven D'Aprano steve at pearwood.info
Sun Aug 7 07:36:05 CEST 2011


Eric Snow wrote:

> Of the three code blocks, functions are the only ones for whom the

[grammar police]
"Whom" is for people. You want "which".
[/grammar police]

(I don't normally correct people's grammar, but to me, this error broke 
the flow of the sentence like being hit in the face with a sock with 
half a brick in it.)


> resulting object and the execution of the code block are separate.  So
> a code object could be executing for the original function or a
> different one that is sharing the code object.

Fairly unusual, but I grant it could happen. I've done it myself :)


> Why not bind the called function-object to the frame locals, rather
> than the one for which the code object was created, perhaps as
> "__function__"?

I'm afraid I can't interpret this (which may be my ignorance rather than 
your fault). The only guess I can make is based on what you say later:

"One new implicit name in locals().

so I presume you mean that the function should see a local variable 
(perhaps called "me", or "this"?) that is bound to itself.

Presumably if a function wants to use that same name as a local, nothing 
bad will happen, since the local assignment will just override the 
implicit assignment. But what about code that expects to see a nonlocal 
or global with the same name?

What happens when two functions, sharing the same code object, get 
called from two threads at the same time? Are their locals independent?

For most uses, standard recursion via the name is good enough, it's only 
a few corner cases where self-reflection (as I call it) is needed. And I 
say that as somebody who does want a way for functions to know 
themselves. I don't think that use-case is so important that it should 
be implicitly added to every function, on the off-chance it is needed, 
rather than explicitly on demand.


> To finish things off, bind to every new code object
> the function for which it was created, perhaps as "co_func".  That way
> you will always know what function object was called and which one the
> code object came from originally.

What benefit will this give? Have you ever looked at a code object and 
said, "I need a way of knowing which function this is from?" If so, I'd 
love to know what problem you were trying to solve at the time!

Code objects don't always get created as part of a function. They can be 
returned by compile. What should co_func be set to then?

Finally, if the function has a reference to the code object, and the 
code object has a reference to the function, you have a reference cycle. 
That's not the end of the world now as it used to be, in early Python 
before the garbage collector was added, but still, there better be a 
really good use-case to justify it.

(Perhaps a weak reference might be more appropriate?)



-- 
Steven




More information about the Python-ideas mailing list