Do I have to specify import when Python script is

2019-09-05 22:49发布

问题:

I am writing a script that I know I will run in Ipython.

I start Ipython as ipython --pylab.

This imports numpy, matplotlib, etc.

So do I have to specify these import statements again in my script?

I did not, and my script did not run.

Thanks for your help.

回答1:

--pylab imports numpy both as * and np. I always use np. to minimize confusion.

If I need numpy in my script, I include the usual import numpy as np line. This lets me run the script from the shell. I can also run it with run ... from within IPython. I could also do an import in Ipython or some other script.

I've never tried omitting the import numpy line, and I don't see any need to start. It doesn't save any time or space. Make a habit of importing what you need, and don't assume the environment will do it for you.

Functions that you define and edit from with in IPython don't need their own import statements.


just tried this script:

def foo1(x):
   return np.sum(x)

def foo2(x):
   return x.sum()

Obviously I can load it with 'run'. And foo2(np.array([1,2,3])) works because the array uses its own method. But foo1 produces a NameError: global name 'np' is not defined.