get the name of lambda

Tim Roberts timr at probo.com
Sat Oct 16 18:40:27 EDT 2004


George Yoshida <ml at dynkin.com> wrote:

>Just out of curiosity, is there any way to get the name of a
>lambda expression? Lambdas are anonymous functions, so it's a
>stupid idea to get the name of it. But if it's possible, how
>could I?
>
>Let's take a simple example:
>  foo = lambda:None
>
>foo.__name__(or foo.func_name) returns '<lambda>'.
>I'm looking for a way to return 'foo', instead of '<lambda>'.

Can't be done.  "foo" is just a name of a reference to something.  The
lambda function has no idea that there happens to be a name called "foo"
that is bound to it.  Consider this:

  foo = boo = doo = lambda:None

  def printMyName(zippy):
      print zippy.__name__

  printMyName( foo )
  printMyName( boo )
  printMyName( doo )

printMyName will get called 3 times with the exact same object.  Inside
printMyName, would you expect the first call to print "foo"?  Why not
"zippy"?
-- 
- Tim Roberts, timr at probo.com
  Providenza & Boekelheide, Inc.



More information about the Python-list mailing list