Have do_nothing as default action for dictionary?

Peter Otten __peter__ at web.de
Sun Sep 3 16:02:08 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):
 
> 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