pythonkeyerrorrenpy

KeyError when trying to get variables' values using globals()


I'm writing a simple mod for a Ren'Py game (to show "hidden" variables).

Information about such variables is kept in a lists of dictionaries; like this (simplified):

icm_data_rowan = [
    {
        'name' : 'Rowan corruption',
        'var_name' : 'avatar.corruption' # Variable's name in the game
        # Other keys/values
    },
    # Other variables
]

There's a Python function to retrieve those variables' values and to put together a string to show in a Ren'Py screen:

def icm_refresh_content():
    global icm_txt
    icm_txt = ''
    icm_data = ICM_data() # Class I'm keeping my variables
    icm_content = icm_data.icm_choose_data(icm_content_to_show) # Function to choose a variables list to show (works fine)
    for entry in icm_content:
        # print('entry['var_name']') # Testing
        try:
            icm_var = globals()[entry['var_name']] # That seems to be a problem!
        except KeyError:
            icm_var = 'NA'
        icm_txt += '{b}' + entry['name'] + ': {color=#FBD315}' + str(icm_var) + '{/color}{/b}{p}'

Which always results with a KeyError/icm_var = 'NA' (KeyError: 'avatar.corruption').

I expect to retrieve those variables' values in the game of course. I get the correct value when I simply type a variable name (avatar.corruption for example) in Ren'Py console. When I print entry['var_name'] in a console (# Testing row) I get the names (like avatar.corruption). So I guess globals()[entry['var_name']] is a problem here? What am I missing/doing wrong?


Solution

  • avatar.corruption is a compound name; only the base name avatar is present in globals.

    Fetch avatar from globals, then then fetch its corruption attribute as a separate step.

    getattr(globals()['avatar'], 'corruption')