def make_test_dice(*outcomes):
"""Return a die that cycles deterministically through OUTCOMES.
>>> dice = make_test_dice(1, 2, 3)
>>> dice()
1
>>> dice()
2
>>> dice()
3
>>> dice()
1
"""
assert len(outcomes) > 0, 'You must supply outcomes to make_test_dice'
for o in outcomes:
assert type(o) == int and o >= 1, 'Outcome is not a positive integer'
index = len(outcomes) - 1
print("Index1: ", index)
def dice():
nonlocal index
index = (index + 1) % len(outcomes)
print("Index2: ", index)
return outcomes[index]
return dice
def main():
foursided = make_test_dice(4,1,2)
foursided()
foursided()
if __name__ == "__main__": main()
So I realize that after calling make_test_dice, when calling foursided it skips the printing of the index1 var and goes to the dice function, as this is a closure. I understand that nonlocal variables refer to variables in the enclosing scope so that changing the var in the nested function would change it in the outer, but what I don't understand is how the variable of index is stored inside the nested function, because it needs a value index when setting the value in dice(). Given my print statements I believe it might be the previous value of index but I thought index would be gone after we exit the local frame of the make_test_dice function.