better lambda support in the future?
Fredrik Lundh
fredrik at pythonware.com
Fri Dec 17 16:56:08 EST 2004
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.
</F>
More information about the Python-list
mailing list