0

it's possible to get in python 2.7.3 the name of a definition like this:

def Newname(self):
    print name_of_def

> "Newname"

Thx,

pux

  • Why would you do this? The name is right there. Just `print "Newname"`. – user2357112 Feb 21 '14 at 22:03
  • http://stackoverflow.com/questions/251464/how-to-get-the-function-name-as-string-in-python – Claus Feb 21 '14 at 22:04
  • @Claus: Different question. That one's about getting the name from outside the function, given the function object. – user2357112 Feb 21 '14 at 22:05
  • @user2357112: I'd say the question I linked is more general than this one. If you have a look at the answers to it, you'll see that both cases are mentioned. – Claus Feb 21 '14 at 22:17

3 Answers3

5
import sys

def newname():
    print sys._getframe().f_code.co_name

newname()
uselpa
  • 18,732
  • 2
  • 34
  • 52
3
import inspect

def Newname():
    return inspect.stack()[0][3]
afkfurion
  • 2,767
  • 18
  • 12
0

use __name__

def Newname():
    return 0

print Newname.__name__
ysakamoto
  • 2,512
  • 1
  • 16
  • 22
  • Nice try, but see the above comments to this question (by Claus and user2357112). – John Y Feb 21 '14 at 22:16
  • @JohnY: You could still print the function's name inside the function and have exactly what the OP asked for. – Claus Feb 21 '14 at 22:26