Obtaining "the" name of a function/method

Ned Batchelder ned at nedbatchelder.com
Sun Nov 17 14:34:15 EST 2013


On Sunday, November 17, 2013 2:24:19 PM UTC-5, John Ladasky wrote:
> 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.

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

    >>> def foo(): pass
    ...
    >>> foo.__name__
    'foo'
    >>> bar = foo
    >>> bar.__name__
    '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.



More information about the Python-list mailing list