[Python] Locals() strange behaviour python?

Discussão em 'Python' iniciado por Stack, Março 10, 2025.

  1. Stack

    Stack Membro Participativo

    Why does this not work ?

    Python 3.11.6 (main, Oct 8 2023, 05:06:43) [GCC 13.2.0] on linux
    Type "help", "copyright", "credits" or "license" for more information.
    condition ={'RAPPORT': 1, 'COMPA': 0.815, 'varie': 'N_GRAIN'}
    N_GRAIN, RAPPORT, COMPA, ACC, FREQ = 0.,0.,0.,0.,0.
    print(locals()['RAPPORT'])
    0.0
    match = all(condition[key] == locals()[key] for key in condition if key != 'varie')

    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <genexpr>
    KeyError: 'RAPPORT'


    I do not understand why it gives me a KeyError, as 'RAPPORT' is in condition and in locals() !?

    I reproduced it on python2 but with different key error. Here is the code :

    Python 2.7.18 (default, Oct 15 2023, 16:43:11)
    [GCC 11.4.0] on linux2

    Type "help", "copyright", "credits" or "license" for more information.
    condition ={'RAPPORT': 1, 'COMPA': 0.815, 'varie': 'N_GRAIN'}
    N_GRAIN, RAPPORT, COMPA, ACC, FREQ = 0.,0.,0.,0.,0.
    print(locals()['RAPPORT'])
    0.0
    match = all(condition[key] == locals()[key] for key in condition if key != 'varie')
    Traceback (most recent call last):
    File "<stdin>", line 1, in <module>
    File "<stdin>", line 1, in <genexpr>
    KeyError: 'COMPA'

    Continue reading...

Compartilhe esta Página