Note that there are some explanatory texts on larger screens.

plurals
  1. POhow to get function's name from within the function (or kind of "self" reference to the function)?
    text
    copied!<p><a href="https://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python/255297#255297">This answer</a> shows that there is a built-in <code>__name__</code> attribute of a function which can be used from <strong>outside</strong> the function, i.e. <code>print f.__name__</code>. However, how can I get this attribute from <strong>within</strong> the function itself?</p> <p>Just using unqualified <code>__name__</code> does not help: <code>print __name__</code> prints <code>__main__</code>.</p> <p>Using <code>print f.__name__</code> from within <code>f()</code> looks stupid - I can type <code>"f"</code> just as well.</p> <p>Alternatively, is there a kind of <code>self</code> object for functions, i.e. can I get a pointer to the function that is executing in a common way?</p> <p>I don't like the method proposed in <a href="https://stackoverflow.com/questions/245304/how-do-i-get-the-name-of-a-function-or-method-from-within-a-python-function-or-me">this question</a> - it feels that hacking the stack for such simple task is not the proper way. </p> <p><strong>Motivation</strong>: I have a dictionary of <code>{keyword:function}</code>, the keywords are read from the input and an appropriate function is executed. I want each function to be executed only once, so I want each function to register itself in some data structure when executed. I know I can do it in the dictionary itself, but I thought of using a separate data structure for this.</p> <p>Python version is 2.6.4 BTW</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload