Search code examples
pythondictionarylazy-evaluation

Set a value in a dict only if the value is not already set


What is the most pythonic way to set a value in a dict if the value is not already set?

At the moment my code uses if statements:

if "timeout" not in connection_settings:
    connection_settings["timeout"] = compute_default_timeout(connection_settings)

dict.get(key,default) is appropriate for code consuming a dict, not for code that is preparing a dict to be passed to another function. You can use it to set something but its no prettier imo:

connection_settings["timeout"] = connection_settings.get("timeout", \
    compute_default_timeout(connection_settings))

would evaluate the compute function even if the dict contained the key; bug.

Defaultdict is when default values are the same.

Of course there are many times you set primative values that don't need computing as defaults, and they can of course use dict.setdefault. But how about the more complex cases?


Solution

  • This is a bit of a non-answer, but I would say the most pythonic is the if statement as you have it. You resisted the urge to one-liner it with __setitem__ or other methods. You've avoided possible bugs in the logic due to existing-but-falsey values which might happen when trying to be clever with short-circuiting and/or hacks. It's immediately obvious that the compute function isn't used when it wasn't necessary.

    It's clear, concise, and readable - pythonic.