better lambda support in the future?
Bengt Richter
bokr at oz.net
Fri Dec 17 23:49:26 EST 2004
On Fri, 17 Dec 2004 22:56:08 +0100, "Fredrik Lundh" <fredrik at pythonware.com> wrote:
>Michael DeHaan wrote:
>
>> True enough, but suppose you want a hash of anonymous functions as
>> opposed to just a lexical? This is where lambas are nice to have.
>> Totally agreed about a small use here and there, but they do have some
>> use in dispatch tables, as they are a lot easier to read sometimes
>> than very long case statements.
>
>standard pattern:
>
>dispatch = {}
>
>def handle_a(...):
> ...
>dispatch["a"] = handle_a
>
>def handle_b(...):
> ...
>dispatch["b"] = handle_b
>
>def handle_c(...):
> ...
>dispatch["c"] = handle_c
>
>if you cannot think of a suitable name for a given case, you can
>name them all "case". for further encapsulation, you can put this
>in a class definition; dispatch will then become a dictionary con-
>taining unbound methods. if the case names all happen to be valid
>Python literals, you can get rid of the dispatch dictionary, and use
>getattr(self, "handle_" + case) to locate the right bound method (or
>if speed is important, use dir() to preload a dispatch dictionary with
>handlers). etc.
>
Looks like your standard pattern could be updated:
>>> dispatch = {}
>>>
>>> def dispvia(name):
... def _(f, name=name):
... dispatch[name] = f
... return f
... return _
...
>>> @dispvia('a')
... def handle_a(): pass
...
>>> @dispvia('b')
... def handle_b(): pass
...
>>> @dispvia('c')
... def handle_c(): pass
...
>>> for t in sorted(dispatch.items()): print '%5s: %r'%t
...
a: <function handle_a at 0x02EE8E9C>
b: <function handle_b at 0x02EE8ED4>
c: <function handle_c at 0x02EE8F0C>
Had to try this experiment:
>>> dispatch = {}
>>> def dispvia(name):
... def _(f, name=name):
... dispatch[name] = f
... return dispatch
... return _
...
>>> @dispvia('a')
... def dispatch(): return 'dispatched a'
...
>>> @dispvia('b')
... def dispatch(): return 'dispatched b'
...
>>> @dispvia('c')
... def dispatch(): return 'dispatched c'
...
>>> for t in sorted(dispatch.items()): print '%5s: %r'%t
...
a: <function dispatch at 0x02EE8F44>
b: <function dispatch at 0x02EE8F7C>
c: <function dispatch at 0x02EE8FB4>
>>> for k in dispatch: print dispatch[k](),
...
dispatched a dispatched c dispatched b
>>> for k in sorted(dispatch): print dispatch[k](),
...
dispatched a dispatched b dispatched c
Hm... this seems like an interesting opening ;-)
Regards,
Bengt Richter
More information about the Python-list
mailing list