dict.get(key, default) evaluates default even if key exists

2QdxY4RzWzUUiLuE at potatochowder.com 2QdxY4RzWzUUiLuE at potatochowder.com
Sun Dec 20 08:45:50 EST 2020


On 2020-12-19 at 22:29:34 +0100,
Roel Schroeven <roel at roelschroeven.net> wrote:

> What could be useful in some use cases, I think, is a wrapper function
> that evaluates the function lazily:
> 
>     def dict_get_lazily(d, key, fnc, *args, **kwargs):
>         try:
>             return d[key]
>         except KeyError:
>             return fnc(*args, **kwargs)
> 
>     some_var = dict_get_lazily(d, 'spam', some_function, 31, 11)

There's no need to pass all those arguments through dict_get_lazily, and
the language already has a way to evaluate an expression lazily:

    def dict_get_lazily(d, key, f):
        try:
            return d[key]
        except KeyError:
            return f()

    some_var = dict_get_lazily(d, 'spam', lambda: some_function(31, 11))

So, beyond a cache (of which there are many variations and many
implementations for many use cases), what are the use cases for an
entire dictionary of lazily computed values?  And if my application has
to know when to access d['key'] directly and when to call
dict_get_lazily(d, 'key', f), then whom am I fooling by "hiding" the
lazy evaluation?  But if I always call dict_get_lazily when I access d,
then why do those two or three lines belong in the standard library
instead of my application or my private toolbox?


More information about the Python-list mailing list