Name of the function

O

Olaf Meding

I am looking for a way to get at the name of the function (while
executing code inside the function) without (!) knowing the name of
the function.

The code below works, but requires the name of the function. I am
looking for a way to do the same w/o specifying the name of the
function.

def olaf():
# requires name of the function
print olaf.__name__

# this does not work
print self.__name__
 
A

anton muhin

Olaf said:
I am looking for a way to get at the name of the function (while
executing code inside the function) without (!) knowing the name of
the function.

The code below works, but requires the name of the function. I am
looking for a way to do the same w/o specifying the name of the
function.

def olaf():
# requires name of the function
print olaf.__name__

# this does not work
print self.__name__

This seems to work:

def foo():
print inspect.currentframe().f_code.co_name

regards,
anton.
 
O

Olaf Meding

Is there a way to do this w/o importing another module?

Yes this is what I was looking for except the code below requires
importing module inspect.
def foo():
print inspect.currentframe().f_code.co_name

Thanks much for your reply.


Olaf
 
T

Terry Reedy

anton muhin said:
This seems to work:

def foo():
print inspect.currentframe().f_code.co_name

as does this ...
f
.... as long as 'f' remains bound to that function in the same module, which
it will unless rebound either from within or without.

Terry J. Reedy
 
A

anton muhin

Olaf said:
Is there a way to do this w/o importing another module?

Yes this is what I was looking for except the code below requires
importing module inspect.
I'm afraid that there is no way, at least none I'm aware of (except for
Terry Reed suggestion, but I think it's not what you are looking for).

Why you don't want to import a module?

regards,
anton.
 
F

Francis Avila

anton muhin wrote in message ...
You could use sys instead, which is IIRC initialized at python start-up,
even though the name isn't put in the namespace until 'import sys'. So
strictly speaking, it's still importing, but there is no overhead.

sys._getframe().f_code.co_name
I'm afraid that there is no way, at least none I'm aware of (except for
Terry Reed suggestion, but I think it's not what you are looking for).

Why you don't want to import a module?

I'll second that. I'll even ask why you want the original binding name of
the function. (When functions are first-class, the "name of the function"
becomes a bit meaningless.) What are you doing? We might be able to
suggest something better.
 

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

No members online now.

Forum statistics

Threads
474,175
Messages
2,570,942
Members
47,490
Latest member
Finplus

Latest Threads

Top