Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it safe to use the variable from dictionary comprehension during error handling?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading