how can I get the name of a method inside it?

  • Thread starter Sébastien Vincent
  • Start date
S

Sébastien Vincent

I would like to know if it's possible to retrieve the name of a method when
you're inside it. For example, in the following script, I would like to
assign _s so that it prints "you are in method1".


***************************************
class Obj1:
def __init__(self):
...

def method1(self):
_s = ???
print "you are in %s" % _s

x = Obj1()
x.method1()
 
M

montyphyton

I would like to know if it's possible to retrieve the name of a method when
you're inside it. For example, in the following script, I would like to
assign _s so that it prints "you are in method1".


***************************************
class Obj1:
def __init__(self):
...

def method1(self):
_s = ???
print "you are in %s" % _s

x = Obj1()
x.method1()

i'm no expert on the subject, but AFAIK, there's no way to do this.
why not just print "you are in method1"?
what are you exactly trying to do?
 
A

Alex Martelli

Sébastien Vincent said:
I would like to know if it's possible to retrieve the name of a method when
you're inside it. For example, in the following script, I would like to
assign _s so that it prints "you are in method1".


***************************************
class Obj1:
def __init__(self):
...

def method1(self):
_s = ???
print "you are in %s" % _s

For debugging purposes,

_s = sys._getframe(0).f_code.co_name

should work (after you've done an "import sys" somewhere appropriate, of
course;-). The _ in front of _getframe, as well as the klunkiness of it
all, are all indications that this is _not_ recommended for "production
use" -- like most of Python's introspection features, it IS chiefly
meant for debugging purposes.


Alex
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,770
Messages
2,569,584
Members
45,075
Latest member
MakersCBDBloodSupport

Latest Threads

Top