%%timeit magic command and variable set to global in function

Question:

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}")

Answers:

Ok, I’ve sort of figured it out, but it’s weird. The short answer is to add a global variable at the very beginning.

%%timeit -n 5 -r 5

global variable

variable = 0

def func():
    
    global variable
    variable += 1

func()


assert (variable == 1)

I’m not sure of the specifics, but I think %%timeit is limiting the scope of your initial variable declaration while the global variable inside your function has larger scope. You can see this in action by removing the first global variable and printing out your variable inside the func.

%%timeit -n 5 -r 5

# global variable

variable = 0

def func():
    
    global variable
    variable += 1
    # Running this multiple times without global variable
    # above will show that this variable is somehow different
    # in scope
    print(variable)

func()


assert (variable == 1)

Manually re-running this block will show that the variable inside function will continue to iterate without resetting.

Answered By: Michael Cao