Here is a MRE:
%%timeit
variable = 0
def func():
global variable
variable += 1
func()
assert (variable == 1)
It works perfectly without the magic command %%timeit.
I'm not sure I understand why it doesn't work when I add the magic command. It seems that it's due to the fact that the variable variable got set to global.
I'm using VSCode and Python 3.11.1
EDIT after It_is_Chris comment suggesting it was just an AssertionError.
This doesn't work either:
%%timeit
variable = 0
def func():
global variable
variable += 1
func()
print(f"Variable is {variable}")
Ok, I've sort of figured it out, but it's weird. The short answer is to add a
global variableat the very beginning.I'm not sure of the specifics, but I think
%%timeitis limiting the scope of your initialvariabledeclaration while theglobal variableinside your function has larger scope. You can see this in action by removing the firstglobal variableand printing out yourvariableinside the func.Manually re-running this block will show that the
variableinside function will continue to iterate without resetting.