Finding the name of a function while defining it

Steven D'Aprano steve+comp.lang.python at pearwood.info
Thu Dec 27 20:07:41 EST 2012


On Thu, 27 Dec 2012 10:09:01 -0500, Roy Smith wrote:

> In article <50dc29e9$0$29967$c3e8da3$5496439d at news.astraweb.com>,
>  Steven D'Aprano <steve+comp.lang.python at pearwood.info> wrote:
> 
>> On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:
>> 
>> >> > two = lamba : "one"
>> >> > one = two
>> >> 
>> >> > Which one of these is the "name" of the function?
>> [...]
>> > If i call one() and two() respectively, i would like to see "one" and
>> > "two".
>> 
>> I'm afraid you're going to be disappointed. There is no possible way
>> for one() and two() as shown above to report different names, because
>> they are the same function object.
> 
> Well, there is the (yes, I know it's absurd) sledgehammer-and-peanut way
> of getting a stack trace, finding the frame that called your function,
> and parsing the text of that line.
> 
> Never tell a hacker, "no possible way" :-)


1) That is not supported by Python the language, only by certain Python 
implementations. You might be running IronPython with frame support 
turned off, or some other implementation with no frames at all.


2) Even if you have frames, you might not have access to the source code. 
The code may be running from the (CPython) interactive interpreter, or 
from a .pyc or .pyo file.


3) Even if you have the text of the source code, it might be ambiguous 
(e.g. "f(); g(); one(); two()") and you cannot tell which is "the 
current" function call.


4) Or the code may be obfuscated and too hard for you to parse:

eval("eval(''.join('ronnie'[1::2])+chr(40)+chr(41))")

(I expect that you, a human intelligence, can decipher the above, but can 
your parser?)


5) Which also rules out decompiling the byte code and parsing the pseudo-
assembly.

No matter how clever your parser, a sufficiently obfuscated algorithm 
will defeat it.


When I say something is impossible, I mean it is not a promised by the 
language. Naturally there may be ways of accomplishing a task that the 
language does not promise to allow which "only sometimes" works. At 
worst, you can always guess an answer, and hope that you're right!

def get_current_function_name():
    # Only sometimes right.
    return "one" if random.random() < 0.5 else "two"


-- 
Steven



More information about the Python-list mailing list