Consider the following example:
config_parameters = ['PARAM1', 'PARAM2', 'PARAM3']
sample_config = {
'PARAM1': 'Value1',
'PARAM2': 'Value2'
}
try:
# Collects param values from the sample config
config = {k: sample_config[k] for k in config_parameters}
except KeyError as e:
# Tries using comprehension var `k` to advise which variable was missing
raise KeyError(f'Value: "{k}" missing from config file.')
In error handling, it tries to catch key errors that arise during a strict dict lookup step which using dict comprehension. For any caught errors, it attempts to utilize a variable that was assigned during the dict comprehension.
Is this considered safe with Python, or is there any reason to expect that k may not indicate the same value which caused the error?
>Solution :
Variables defined in a comprehension are considered local to the comprehension, so k cannot be used outside of the dict display. (This was a change made in Python 3 to prevent such leakage.)
Assignment expressions were specifically defined to allow the "extraction" of a value from that anonymous namespace, however. (See https://peps.python.org/pep-0572/#scope-of-the-target)
try:
# Collects param values from env vars
config = {k: sample_config[(offending_key := k)] for k in config_parameters}
except KeyError:
raise KeyError(f'Value: "{offending_key}" missing from config file.')
k is local to the comprehension; offending_key is local to whatever scope contains the comprehension.