Finding the name of a function while defining it

Tim Chase python.list at tim.thechases.com
Thu Dec 27 14:32:16 CET 2012


On 12/27/12 04:58, Steven D'Aprano wrote:
> On Wed, 26 Dec 2012 23:46:31 -0800, Abhas Bhattacharya wrote:
> 
>>>> two = lamba : "one"
>>>> one = two
>>>
>>>> Which one of these is the "name" of the function?
> [...]
>> If i call one() and two() respectively, i would like to see "one" and
>> "two".
> 
> I'm afraid you're going to be disappointed. There is no possible way for 
> one() and two() as shown above to report different names, because they 
> are the same function object.
> 
> py> two = lambda : "one"
> py> one = two
> py> one is two
> True
> py> one, two
> (<function <lambda> at 0xb7abd92c>, <function <lambda> at 0xb7abd92c>)

And for similar fun:

  def call(fn, *args, **kwargs):
    return fn(*args, **kwargs)

  two = lambda : "one"
  one = two
  print(call(two))
  print(call(one))

Depending on where in the code you are, the same function object
also has a local name of "fn".  It's madness until you understand
it, and then it's beauty :)

-tkc





More information about the Python-list mailing list