Introspection & Python Functions

Terry Reedy tjreedy at udel.edu
Fri Dec 13 16:59:43 EST 2002


"Mike Dean" <klaatu at evertek.net> wrote in message
news:atdglv$svc$2 at ins22.netins.net...
> I was just playing around with some introspection in Python, and
noticed
> something (I think this has probably been commented on before, but
> anyway...).  It appears there is no way for a function to access
itself
> besides, effectively, globals()['functionname'].
>Why?

Because no one has (to my knowledge) come up with both something
better (for functions) and a rationale for why it should be in the
core.

One could propose that locals be initializes with __self__= <function>
but  __magic__ names are not part of the function schtick.

> What happens to
> recursion if some clever (or otherwise) code renames the function,
then
> repoints its old name to something else?   Suddenly, the function is
> unable to fulfill its destiny.

Right, the recursion gets hosed.  (Which is one reason the interpreter
does not 'remove' tail recursion.)  But note that *any* function
accessing *any* global or builtin is vulnerable to such external
rebindings, so this is nothing new.

> So, is there something I am missing?  Or, if not, why has such a
thing
> missing?  Granted, I can't envision many useful scenarios for such a
thing

Which partly answers your 'Why?' question ;>)

> thing (particularly now that statically nested scopes allow
protection
> for recursive functions by making them inside outer wrappers),

Given that many recursive functions require or benefit from one-time
initialization before starting the looping (possbibly with a change in
parameterization), this is an excellent solution.

> but it seems that it is a hole in Python's introspection.

Two other methods for function self-awareness:

1. Require caller to pass in reference -- f(f,args)
2. Make function a  __call__ method of a class.  IE, if you want a
function to be like a method, make it one.

Terry J. Reedy





More information about the Python-list mailing list