473,805 Members | 2,172 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Accessing func_name from inside a function

I'd like to access the name of a function from inside the function. My
first idea didn't work.
def foo(): .... print func_name
.... foo() Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in foo
NameError: global name 'func_name' is not defined

My second attempt works but looks ugly.
def foo(): .... import inspect
.... print inspect.stack()[0][3]
.... foo()

foo

Is there a standard way of getting the name of a function from inside
the function?

Mar 25 '06 #1
14 3899
James Thiele wrote:
Is there a standard way of getting the name of a function from inside
the function?


No, there isn't.

Martin
Mar 25 '06 #2
James Thiele wrote:
I'd like to access the name of a function from inside the function.


http://aspn.activestate.com/ASPN/Coo...n/Recipe/66062

Kent
Mar 25 '06 #3
OK. But that's just as ugly as my attempt.

Mar 25 '06 #4
"James Thiele" <ja************ ****@gmail.com> writes:
I'd like to access the name of a function from inside the function.


A function, like most other objects in Python, can have any number of
names bound to it without the object being informed. Any of those
names can then be used to reference the object, and the object has no
way of knowing by what name it was referenced.

Because of this fallacy, it's generally considered bad programming
style to want to know "the" name of the current object from inside
that object.

What is it you're trying to achieve?

--
\ "Unix is an operating system, OS/2 is half an operating system, |
`\ Windows is a shell, and DOS is a boot partition virus." -- |
_o__) Peter H. Coffin |
Ben Finney

Mar 26 '06 #5
On Sun, 26 Mar 2006 10:19:36 +1000, Ben Finney wrote:
"James Thiele" <ja************ ****@gmail.com> writes:
I'd like to access the name of a function from inside the function.
A function, like most other objects in Python, can have any number of
names bound to it without the object being informed. Any of those
names can then be used to reference the object, and the object has no
way of knowing by what name it was referenced.

Because of this fallacy,


"You keep using that word. I do not think it means what you think it
means."

*wink*
it's generally considered bad programming
style to want to know "the" name of the current object from inside
that object.


I agree whole-heartedly with Ben's sentiments here, although I can also
point out by example why it might be useful for a function to know it's
own name:

def Ackermann(i, j):
"""Returns the Ackermann function of integers i and j.

The Ackermann function is an example of a function which grows at a
much faster than exponential rate. Ackermann(i, j) for i > 2 grows
even more quickly than 2**2**2**...**2 (where there are j exponents).
It is an example of a recursive function which is not primitively
recursive and was discovered by the German mathematician Wilhelm
Ackermann in 1928.
Ackermann(1, 1) 2 Ackermann(2, 2) 16 Ackermann(2, 3) 65536

The Ackermann function is not defined for i,j <= 0.

See http://en.wikipedia.org/wiki/Ackermann_function
and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
Leiserson, Ronald L Rivest, pp. 451-453.
"""
if i < 0 or j < 0:
raise ValueError(
"arguments to the Ackermann function must be positive")
if i == 1:
return 2**j
if j == 1:
return Ackermann(i-1, 2)
return Ackermann(i-1, Ackermann(i, j-1))

Notice that if you change the name of the function, you have to change it
in no less than three places in the function definition and four places
in the __doc__ string, but a global search and replace is too greedy and
will change too much. As a general principle, it is considered best
practice to code in such a way that if you change something, you only need
to change it in one place.

I guess that the Original Poster wants some magic that allows functions to
do this:

def Ackermann(i, j):
"""Returns the Ackermann function of integers i and j.

The Ackermann function is an example of a function which grows at a
much faster than exponential rate. %MAGIC(i, j) for i > 2 grows
even more quickly than 2**2**2**...**2 (where there are j exponents).
It is an example of a recursive function which is not primitively
recursive and was discovered by the German mathematician Wilhelm
Ackermann in 1928.
%MAGIC(1, 1) 2 %MAGIC(2, 2) 16 %MAGIC(2, 3)

65536

The Ackermann function is not defined for i,j <= 0.

See http://en.wikipedia.org/wiki/Ackermann_function
and 'Introduction to Algorithms' by Thomas H Cormen, Charles E
Leiserson, Ronald L Rivest, pp. 451-453.
"""
if i < 0 or j < 0:
raise ValueError(
"arguments to the Ackermann function must be positive")
if i == 1:
return 2**j
if j == 1:
return %MAGIC(i-1, 2)
return %MAGIC(i-1, %MAGIC(i, j-1))
Now he can easily rename "Ackermann" to "Ack" and need only make the
change in one place.

I suspect that the correct solution to the O.P.'s problem is to think
carefully about the names of your functions in advance.

--
Steven.

Mar 26 '06 #6
Ben Finney <bi************ ****@benfinney. id.au> wrote:
"James Thiele" <ja************ ****@gmail.com> writes:
I'd like to access the name of a function from inside the function.


A function, like most other objects in Python, can have any number of
names bound to it without the object being informed. Any of those


Yes, but, quite independent of the 0+ names BOUND to the object,
function objects, like class and module objects, have ONE "true" name
(which may or may not coincide with one of those bound to the object, if
any) -- the special attribute __name__ (AKA func_name for function
objects only, but I'll stick with __name__ which applies uniformly).

Code in a module can get the module's name by simply accessing global
variable __name__. I see nothing untowards in a desire to access
__name__ from code within a function or a class body, getting the name
of the function or the class respectively rather than the name of the
module they're in... it's just not implemented that way (and can't be
changed until Python 3.0 for backwards compatibility). But proposals for
3.0 can be entertained.

Personally, I'd rather have a 3.0 keyword referring to "the current
object" (module for module toplevel code, class for classbody toplevel
code, function for code within a function) -- say for the sake of
argument the keyword is 'current'; this would allow current.__name_ _ to
have the obvious meaning, and would also allow a few more neat things
(such as natural access to current.__doc__ ).

But if the OP is looking for a Python 2.* solution, then sys._getframe
or module inspect are the only way to go, be they "ugly" as he considers
them, or not.
Alex
Mar 26 '06 #7
Alex Martelli wrote:
Personally, I'd rather have a 3.0 keyword referring to "the current
object" (module for module toplevel code, class for classbody toplevel
code, function for code within a function) -- say for the sake of
argument the keyword is 'current'; this would allow current.__name_ _ to
have the obvious meaning, and would also allow a few more neat things
(such as natural access to current.__doc__ ).


That was my thought too, that what is really desired is a *obvious* way
to get a dependable reference to the current function as you describe here.

A quick experiment... with an obvious result:
def foo(): print foo.__name__ ... foo() foo boo = foo
boo() foo boo.__name__ 'foo' foo = None
boo()

Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 1, in foo
AttributeError: 'NoneType' object has no attribute '__name__'


A "Current" key word would fix this. Or possibly "This" which would be
short for "This object".

This may also relate to suggestions to reduce the need for having self
in the argument list of methods. So if a keyword "This" could mean this
method or function, then "Self" could mean this class. Hmmm, methods
that use "Self" in this way might run into problems, but I havn't had
enough coffee to think it though. ;-)

Cheers,
Ron

Mar 26 '06 #8
James Thiele a écrit :
I'd like to access the name of a function from inside the function. My
first idea didn't work.

def foo():
... print func_name
...
foo()
Traceback (most recent call last):
File "<stdin>", line 1, in ?
File "<stdin>", line 2, in foo
NameError: global name 'func_name' is not defined

My second attempt works but looks ugly.

def foo():
... import inspect
... print inspect.stack()[0][3]
...
foo()


foo

Is there a standard way of getting the name of a function from inside
the function?


You've already got good answers. Now here's another workaround:

class _FooFunction(ob ject):
def __call__(self):
print self.__class__. __name__
foo = _FooFunction()

Mar 26 '06 #9
Ron Adam <rr*@ronadam.co m> wrote:
A "Current" key word would fix this. Or possibly "This" which would be
short for "This object".


I think "This" would cause huge confusion, since in other popular
language the keyword "this" means (a pointer/reference to) "the instance
variable on which the method is being called" -- my use is instead for
"the object of the immediate lexically enclosing scope" (a module,
class, or function). Implementation wouldn't be trivial in today's
CPython, anyway: frames have no references at all to function objects
(only to _code_ objects), and class objects don't even exist untill well
after their top-level code has long finished running; to make Current
possible, these subtle points of semantics would have to be changed in
quite a revolutionary way, especially where classes are concerned.
Alex
Mar 26 '06 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
4808
by: Demian | last post by:
Hi, I developed an OCX in VC++, wich takes a VARIANT as parameter and return a Long as the result of the operation. This VARIANT cames from a client VB6.0 wich send an array of Byte as a VARIANT, so acomplish Autonmation std. I need to access the array inside the variant to load an user-defined struct with it. To do this I used the myvariant->parray.pvData but it didn't work. It seems that the data wasn't there... I tried with...
18
8931
by: Bryan Parkoff | last post by:
"#define" can only be inside the global scope before main() function. "#if" can be tested after "#define" is executed. The problem is that "#define" can't be inside main() function. I do not wish to create multiple functions which they look almost identical in C++ source code. The C++ compiler should be able to compile one Test() function into two almost identical functions before they are translated into the machine language object. ...
4
4411
by: Barry Mossman | last post by:
Hi, I am throwing an exception derived from ApplicationException as follows catch (Exception ex) { throw new MyException("message", ex); } My exception's constructor is: public ExceptionBase(string aMessage, Exception aInnerException): base(aMessage, aInnerException)
4
2447
by: dogpuke | last post by:
I have a class CString. I'm wondering if it's possible to make a global function mystr_cat that does this: CString s1 = "hello"; s1 = mystr_cat("another", "string", "here"); Thus mystr_cat needs to access the "this" part of s1. Or maybe = can be overloaded? Or is this type of thing not allowed?
5
1875
by: Alex Maghen | last post by:
Hi. If I create a WebControl (User Control, actually), I know how, easily, to access the design-time Properties that have been set as Propertiy nodes in the tag used on the ASPX page. But I've never tried having CONTENT inside my Control's Tag, e.g.: <Ax:MyCtl id="Something" runat="server"> Some stuff inside the tag </Ax:MyCtl> How do I access the body from the code of my Control (i.e. above, "Some
1
2104
by: Dave | last post by:
I have the following ASP.NET 2.0 code (simplified here for ease): <asp:Repeater id="SearchResultsRepeater" runat="server"> <ItemTemplate> <uc:SearchResult ID="SearchResult" ResultObject="<%#Container.DataItem%>" runat="server"> <ButtonsTemplate> <uc:ViewButton ID="ViewButton" ListingReference='<%#Eval("ListingReference")%>' runat="server" /> </ButtonsTemplate>
6
1568
by: smoermeli | last post by:
#include <iostream> #include <vector> class Thing { private: int value; friend class Person; public: int getValue() { return value; } void setValue(const int val) { value=val; }
1
2396
by: Hunter | last post by:
I am writing a script that needs to send some emails. And I've used smtplib in the past and it is pretty easy. But I thought, gee it would be easier if I could just call it as a function, passing the from, to, subject, and message text. So I wrote it up as a function and it sort of works, but I get a weird error. When it runs it inserts a "\t" tab character before each item during the send portion (which I can see when I turn on...
0
1364
by: gaya3 | last post by:
Hi, For our swing application we are using derby database. Since its desktoop application, we are providing the application as jar to the clients. But issue is in finding the database. Derby database url is not recognised inside the jar. we have the entry as jdbc:derby:src\DerbyDSLS001 we also tried as jdbc:derby:jar:(C:/Test.jar)src/DerbyDSLS001 ==> Its working fine. The bottleneck in this is jar need to be placed inside "C:" else...
0
9718
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
10107
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
9186
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
7649
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6876
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
5544
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
5678
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
4327
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
3846
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.