Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why xrange is not defined when I'm not using xrange in the first place?

In the following code snippet,

if evaluation_data: 
    n_data = len(evaluation_data)
    n = len(training_data)
    evaluation_cost, evaluation_accuracy = [], []
    training_cost, training_accuracy = [], []
    for j in list(range(epochs)):
        random.shuffle(training_data)
        mini_batches = training_data[k:k+mini_batch_size]

you can see that I'm not using xrange.Although the code was written to run on pyhton2, I refactored to run it on python3. However, I'm keep getting the follwoing error:

................................Directory/network2.py", line 147, in SGD
    for j in list(range(epochs)):
NameError: name 'xrange' is not defined

In the beginning, I used only range(). Then after learning that range() is not a list in python3 I did list(range()). However, I'm keep getting the error for xrange in both revised cases. Would appreciate if someone can help.

like image 322
Kalia Dona Avatar asked Oct 19 '17 20:10

Kalia Dona


1 Answers

You are running stale bytecode, restart Python.

Python compiles source code to bytecode, and interprets the latter. This means the interpreter doesn't work with the source code once compiled.

However, us humans can't read bytecode very well, so when there is an exception and the interpreter wants us to understand where things went wrong, it would like to show you the source code again. Thus the source code is loaded on demand when there is a traceback to be shown, and lines are taken from the source code based on information recorded with the bytecode.

In your case, you are running bytecode that uses the name xrange. But you have already corrected the source code to use range instead. The bytecode throws an exception, and Python helpfully loads the source code from disk, and shows the already corrected sourcecode.

The solution is to tell Python to re-compile the source code, by restarting. If restarting doesn't help, then Python has determined that the source code is older than the bytecode it has cached. Delete the __pycache__ directory next to your source code to clear the bytecode cache, and remove any .pyc file that might be sitting in the same directory as your source.

Note that you can drop the list() call; you don't have to have a list for the for loop to work; for j in range(epoch): works just fine.

like image 72
Martijn Pieters Avatar answered Nov 10 '22 02:11

Martijn Pieters