-1

When try to %timeit in Jupyter Notebook got error; Without it working fine.

UnboundLocalError: local variable 'a' referenced before assignment

import torch
a = torch.rand(10)
b = torch.rand(10)
%timeit a = torch.where(b > 0.5, torch.tensor(0.), a)

What is happening here?

Red
  • 26,798
  • 7
  • 36
  • 58
Dishin H Goyani
  • 7,195
  • 3
  • 26
  • 37
  • Does this answer your question? [ipython %timeit "local variable 'a' referenced before assignment"](https://stackoverflow.com/questions/48269712/ipython-timeit-local-variable-a-referenced-before-assignment) – Shiva May 25 '20 at 14:54

1 Answers1

2

At first, I thought that's because %timeit only evaluates the time run by functions. But thanks to @Shiva who told me it can calculate the execution time of other things. And I checked the documentation here, and I found out this is true.

So, according to this answer, %timeit has a problem with re-assignment as the re-assignment to a causes the function to have an a local variable, hiding the global. In other words, you can use any other variable other that a to assign it to torch.where:

#this works
%timeit c = torch.where(b > 0.5, torch.tensor(0.), a) #c instead of a

# this works
%timeit torch.where(b > 0.5, torch.tensor(0.), a)

# this doesn't work
%timeit a = torch.where(b > 0.5, torch.tensor(0.), a)
Anwarvic
  • 12,156
  • 4
  • 49
  • 69
  • 1
    The argument to `%timeit` need not be a function, it can be any expression or statement(including a function statement) – Shiva May 25 '20 at 14:51
  • yeah... you're right. I didn't know that till now. Gonna edit my answer. Thanks – Anwarvic May 25 '20 at 14:53