Obtaining "the" name of a function/method

J

John Ladasky

Hi, folks,

Here's a minimal Python 3.3.2 code example, and its output:

=================================================

def foo():
pass

print(foo)
bar = foo
print(bar)

=================================================

<function foo at 0x7fe06e690c20>
<function foo at 0x7fe06e690c20>

=================================================

Obviously, Python knows that in my source code, the name that was bound to the function I defined was "foo". The print function even returns me the name "foo" when I bind a new name, "bar", to the same function. This is useful information that I would like to obtain directly, rather than having to extract it from the output of the print statement. How can I do this? Thanks.
 
N

Ned Batchelder

Hi, folks,

Here's a minimal Python 3.3.2 code example, and its output:

=================================================

def foo():
pass

print(foo)
bar = foo
print(bar)

=================================================

<function foo at 0x7fe06e690c20>
<function foo at 0x7fe06e690c20>

=================================================

Obviously, Python knows that in my source code, the name that was bound to the function I defined was "foo". The print function even returns me thename "foo" when I bind a new name, "bar", to the same function. This is useful information that I would like to obtain directly, rather than having to extract it from the output of the print statement. How can I do this? Thanks.

Functions have a __name__ attribute, which is the name they were defined as:
'foo'

Like many statements in Python, the def statement is really performing an assignment, almost as if it worked like this:

foo = function_thing(name="foo", code=......)

The function object itself has a name, and is also assigned to that name, but the two can diverge by reassigning the function to a new name.

--Ned.
 
T

Tim Chase

Functions have a __name__ attribute, which is the name they were
defined as:

'foo'

which they have even in less-than-useful situations:

(lambda s: s.lower()).__name__

accurately returns that its name is "<lambda>". So you get what you
pay for ;-)

-tkc
 

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
473,769
Messages
2,569,580
Members
45,055
Latest member
SlimSparkKetoACVReview

Latest Threads

Top