Skip to content
Advertisement

python: numpy runs script twice

when I import numpy to my python script, the script is executed twice. Can someone tell me how I can stop this, since everything in my script takes twice as long?

Here’s an example:

JavaScript

And the output is:

JavaScript

So, is my script first executed with normal python and then with numpy again? Maybe I should say that I have not worked with numpy yet and just wanted to start and test it.

Cheers

Advertisement

Answer

Your script, being named numpy.py, unintentionaly imports itself. Since module-level code gets executed when imported, the import line causes it to run, then once the imoprt is completed, it runs the rest again.

(An explanation about why a script can import itself)

Suggestions:

  1. rename your script to something other than numpy.py
  2. use the if __name__=='__main__' idiom (you should always use it in your scripts)

Other than that, as already pointed out, from numpy import * is strongly discouraged. Either use import numpy or the common import numpy as np.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement