Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

Ok, I’ve sort’ve 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading