python programming style question:
You have two dicts, A and B. if the key 'foo' exists in B, set the key foo in A to value of B['foo'] (and don't throw an exception if not)
One way to code this would be:
if 'foo' in B:
A['foo'] = B['foo']
python programming style question:
You have two dicts, A and B. if the key 'foo' exists in B, set the key foo in A to value of B['foo'] (and don't throw an exception if not)
One way to code this would be:
if 'foo' in B:
A['foo'] = B['foo']
some code I encountered in the wild did:
b_foo_value = B.get("foo", None)
if b_foo_value:
A["foo"] = b_foo_value
but with a few extra lines for logging
my first attempted at rewriting this was the OP version, the if. But then I was like NAH WHY NOT JUST:
try:
A['foo'] = B['foo']
except KeyError:
pass
but ruff told me no no, don't do that. do this instead:
import contextlib
with contextlib.suppress(KeyError):
A['foo'] = B['foo']
which is not an option I would have considered and I'm wondering if other python programmers agree with that style. My python style unfortunately lags behind because I was stuck in the python 2 mines for so long, so I've missed out on a lot of the python 3 features like this.