Keep getting UnboundLocalError: local variable 'Key' referenced before assignment

If this template helps then use it. If not then just delete and start from scratch.

OS (Win11):
PsychoPy version (e.g. 2024.1.1):
Standard Standalone? (y/n) y:
What are you trying to achieve?: I try to run an experiment. It uses a loop and shows a stimulus and then the participant should react with a key press. Then the next trail begins. The key is different in each trail, so I added a excel file that defines the allowed keys per trial.

What did you try to make it work?: Searching the forum. All the related topics are not applicable or do not solve the error.

What specifically went wrong when you tried that?:
Basically, whenever I try to use the allowedKeys (variable names ‘Key’) via the file, I get the message

I don’t know the appropriate default value for a ‘allowedKeys’ parameter. Please email the mailing list about this error

and

UnboundLocalError: local variable ‘Key’ referenced before assignment

The file should be set up correctly, the keys are defined for example as [‘m’], and useing the file for different stimuli does work perfectly. Just not for the keyboard component.

I attache a minimal example:
Experiment
untitled.psyexp (14.4 KB)
Excel file
001_Test.xlsx (8.5 KB)

Help is much appreciated

In the keyboard component put [Key] instead of Key (because there is just a single key allowed)

In the Excel file put just the letter (delete [‘’ ])

New files:

untitled.psyexp (16.2 KB)
001_Test.xlsx (8.3 KB)

There is an error in the program code that tries to convert the content of the Key variable.

The following statements create a local variable with the same name as the global parameter variable.

                    "    elif not ',' in {0}:\n"
                    "        {0} = ({0},)\n"
                    "    else:\n"
                    "        {0} = eval({0})\n"
                    .format(allowedKeys))

This creates the output:

                    elif not ',' in Key:
                        Key = (Key,)
                    else:
                        Key = eval(Key)

The two assignment statements cause a local Key variable to be created. The local variable overloads the global variable with the same name which contains the allowedKeys parameter. This leads to the error message “local variable ‘Key’ referenced before assignment”.