Have do_nothing as default action for dictionary?
Peter Otten
__peter__ at web.de
Sun Sep 3 16:13:28 EDT 2017
Christopher Reimer via Python-list wrote:
> Greetings,
>
> I was playing around this piece of example code (written from memory).
>
>
> def filter_text(key, value):
>
> def do_nothing(text): return text
>
> return {'this': call_this,
>
> 'that': call_that,
>
> 'what': do_nothing
>
> }[key](value)
>
>
> Is there a way to refactor the code to have the inner do_nothing
> function be the default action for the dictionary?
If it does nothing, why invoke it at all?
LOOKUP = {"this": call_this, ...}
def filter_text(key, value):
if key in LOOKUP:
return LOOKUP[key](value)
return value
If there are much more hits than misses:
def filter_text(key, value):
try:
process = return LOOKUP[key]
except KeyError:
return value
return process(value)
If you insist on invoking a noop func:
def do_nothing(text): return text
def filter_text(key, value):
return LOOKUP.get(key, do_nothing)(value)
With a collections.defaultdict (will grow to comprise new keys):
LOOKUP = defaultdict(LOOKUP, lambda: do_nothing)
def filter_key(key, value):
return LOOKUP[key](value)
> The original code was a series of if statements. The alternatives
> include using a lambda to replace the inner function or a try-except
> block on the dictionary to return value on KeyError exception.
>
> What's the most pythonic and fastest?
>
> Thank you,
>
> Chris R.
>
More information about the Python-list
mailing list