annonymous functions -- how to

Bengt Richter bokr at oz.net
Wed May 4 19:34:10 EDT 2005


On Wed, 04 May 2005 23:08:16 +0200, Peter Otten <__peter__ at web.de> wrote:

>Mayer wrote:
>
>> I would like to define a very large annonymous function, one with
>> several statements in sequence. I know how to define annonymous
>> functions, but I don't know how to define a sequence of statements in
>> their body. Can this be done in Python? If so, how?
>
>No, it can't. Why do you prefer your function to be anonymous?
>
Depends on what you mean by "anonymous" ;-)

 >>> def foo():
 ...    print 'statement 1'
 ...    print 'statement 2'
 ...    print 'statement etc'
 ...
 >>> foo.__name__ = '' # make really anonymous
 >>> fooholder = [foo]
 >>> del foo # forget name binding too
 >>> dir()
 ['__builtins__', '__doc__', '__name__', 'fooholder']
 >>> fooholder.append(lambda: 'not that anonymous ;-)')
 >>> fooholder
 [<function  at 0x02EE8D84>, <function <lambda> at 0x02EE8D14>]
 >>> [f.__name__ for f in fooholder]
 ['', '<lambda>']
 >>> fooholder[0](), fooholder[1]()
 statement 1
 statement 2
 statement etc
 (None, 'not that anonymous ;-)')

Regards,
Bengt Richter



More information about the Python-list mailing list