Accessing func_name from inside a function

J

James Thiele

I'd like to access the name of a function from inside the function. My
first idea didn't work.
.... print func_name
....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.
.... import inspect
.... print inspect.stack()[0][3]
....foo

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

=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=

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

No, there isn't.

Martin
 
B

Ben Finney

James Thiele said:
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?
 
S

Steven D'Aprano

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.
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.
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.
 
A

Alex Martelli

Ben Finney said:
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
 
R

Ron Adam

Alex said:
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:
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
 
A

Alex Martelli

Ron Adam said:
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
 
E

Eyal Lotem

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

*wink*


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.

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.

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))

Another possibility would be:

def recursive_func(func):
def new_func(*args, **kw):
return func(new_func, *args, **kw)
return new_func

@recursive_func
def Ackermann(recurse, i, j):
# yadda yadda
recurse(i-1, ...), recurse(y-2, ...)
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.

By the way, the "real" problem here is referencing by name, rather than
using "true" references. Which is the result of using a textual language.
The "real" solution would be to store real-references to the function and
only present the name in a graphical interface.
 
A

Alex Martelli

James Thiele said:
I'd like to access the name of a function from inside the function. My
first idea didn't work.

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

So, define it -- as a function, of course:

def func_name():
import sys
return sys._getframe(1).f_code.co_name

def foo():
print func_name()

def bar():
print func_name()

No doubt you'll object that the internals of func_name are "ugly", but
the point is that it can be hidden anywhere you like, so its internals
are as irrelevant as they would be if it was a built-in.


Alex
 
R

Ron Adam

Alex said:
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

Yes, I figured it would not be an easy or simple addition. An easier
alternative might be to be able to limit specific name rebindings. Then
some names could be depended on to always point to a specific object.
Something like that would need to be used sparingly I think.

Cheers,
Ron
 
B

Bruno Desthuilliers

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


... print func_name
...

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.


... import inspect
... print inspect.stack()[0][3]
...

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(object):
def __call__(self):
print self.__class__.__name__
foo = _FooFunction()
 
S

Scott David Daniels

Eyal said:
By the way, the "real" problem here is referencing by name, rather than
using "true" references. Which is the result of using a textual language.
The "real" solution would be to store real-references to the function and
only present the name in a graphical interface.

There is a problem with this attitude (to which I used to subscribe).
Just as what constitutes a mathematical proof is a social agreement
among mathematicians, programmers need to be able to read programs
by other programmers. People do not communicate in data structures.
I worked with LML, a lazy ML variant that (among other things) allowed
specification of the print form of structures. I wound up debugging
(for a nasty 12 hours) a program which printed identically to the
correct program, but was not, in fact, the correct program. That one
experience has convinced me that programs are defined in print, not
structures.

--Scott David Daniels
(e-mail address removed)
 
E

Eyal Lotem

Scott said:
There is a problem with this attitude (to which I used to subscribe).
Just as what constitutes a mathematical proof is a social agreement
among mathematicians, programmers need to be able to read programs
by other programmers. People do not communicate in data structures.
I worked with LML, a lazy ML variant that (among other things) allowed
specification of the print form of structures. I wound up debugging
(for a nasty 12 hours) a program which printed identically to the
correct program, but was not, in fact, the correct program. That one
experience has convinced me that programs are defined in print, not
structures.

Well, what you describe is a hidden semantic difference, which is a problem
of the view, not of the representation. As long as the view can display
the details of the program in their entirety, text has no advantage in this
aspect. There is no reason why replacing the textual backend with a richer
object model and true references would prevent a simple viewer that renders
the programs as simple text similar to the way they look today. It would
seem almost equivalent but suddenly easy renames, diff tracking for source
control, and semantic editing would not only be possible but easy.
 

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

Staff online

Members online

Forum statistics

Threads
474,291
Messages
2,571,453
Members
48,135
Latest member
papaoso

Latest Threads

Top