[Tutor] getting the current method name

Jeff Shannon jeff@ccvcorp.com
Thu Apr 17 19:29:01 2003

Magnus Lycke wrote:

> The docs say about sys._getframe that "This function
> should be used for internal and specialized purposes only."
> What does this really imply? That we can't expect the API
> to remain? 

I think it's just indicating pretty much what I'd said in my response -- 
that this is something that's dependent on the internal structure of the 
interpreter, rather than something that's a meaningful part of the 
language definition.  It seems risky to assume that future/alternate 
versions of the Python interpreter will always use the same execution 
frame architecture -- odds of it actually changing may not be that 
great, but I think this is an appropriate example of what the Law of 
Demeter tries to discourage.  Obviously, someone who's writing a 
debugger or a code-inspection tool will need to be able to do this sort 
of thing, but it's not really intended for general usage.  (A further 
hint along those lines is the use of a leading underscore on 
_getframe(), indicating that this function is intended as a "private" 
internal function rather than as part of the public API.  As is typical 
of Python, you're allowed access to internals, but you should always be 
aware that you're using them at your own risk.)

I stand by my earlier contention that, absent a truly compelling reason 
to muck about in the guts of the interpreter, the O.P. can probably find 
a more appropriate solution to their problem than this.  To be honest, I 
can't think of a reason to *need* the name of the current 
method/function, except maybe in the specialized cases of a debugger or 
code inspector.  Typically, if I need the name of a method, I'd need it 
to invoke an arbitrary method via getattr(), and I'd probably be drawing 
that name from a dictionary somewhere.  But when I'm writing a function, 
I know what name I'm giving it, so I don't really need a way to drag 
that name out of the interpreter.

Jeff Shannon
Credit International