Anonymous functions (and classes)
logistix
logstx at bellatlantic.net
Thu Apr 4 17:14:12 EST 2002
>
> I would like to be able to define anonymous functions and classes by
> omitting the function or class name normally found after the def or
> class keyword. For example, the following two function definitions would
> be equivalent:
>
That's why god created nested scopes (or one of the reasons at least):
>>> def factory():
... def foo():
... print "bar"
... class bar:
... def foo(self):
... print "baz"
... instance = bar()
... return foo, instance
...
>>> a,b = factory()
>>> a()
bar
>>> b.foo()
baz
>>> foo()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'foo' is not defined
>>> x = bar()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'bar' is not defined
>>>
And if you want to clobber factory() from the namespace:
>>> del factory
>>> factory()
Traceback (most recent call last):
File "<interactive input>", line 1, in ?
NameError: name 'factory' is not defined
More information about the Python-list
mailing list