Trouble with variable scope

indexes_1 is a local variable doesn’t exist outside the scope of that function.

So you have two possible issues here -

  1. check your indentation on your code - the second block is not part of your function so the variable is out of scope. Assuming you have pasted it correctly of course :slight_smile: then try this :

  def question_index(self):
    question_row = self.my_list[self.index]
    indexes_1 = question_row['question_index']
    print(indexes_1)  # this prints the value I'm looking for

    self.question_index()
    print (indexes_1)
  1. If it must be accessible throughout your form then, as @divyeshlakhotia suggests, you should make it a form class-wide property by prepending self to it.

If you use self.indexes_1 then make sure you set it to a value before you read it. I think it’s good practise to initialise properties in the init method. So something like this :

def __init__(self, **properties):
    self.init_components(**properties)

    self.indexes_1 = 0

This ensures any attempt to read the value before you set it doesn’t give you nonsense or an error.

Some info on variable scope in Python :
https://pythonbasics.org/scope/

1 Like