GarethC
GarethC

Reputation: 155

Spyder not recognising imported terms

I'm using Spyder 3.1.2 (Python 2.7.13). As part of the startup, the IPython console is set to "Automatically load Pylab and NumPy modules".

When i want to use the method NumPy.zeros(shape), I can just call it in the IPython console as zeros:

In [12]: zeros(5)
Out[12]: array([ 0.,  0.,  0.,  0.,  0.])

My problem comes when trying to call the same zeros function from a separate python file.

If I create a function UseZeros() in a file Test1.py

"""
filename: Test1.py
"""

def UseZeros():
    return zeros(4)

And I call it from a separate file, Test2.py:

"""
filename: Test2.py
"""

import Test1

testArr1 = zeros(5)
testArr2 = Test1.UseZeros()

In this script, testArr1 = zeros(5) works fine, but when calling Test1.UseZeros(), I get an error stating the global name 'zeros' is not defined.

File "C:/Users/Gareth/Test2.py", line 8, in testArr2 = Test1.UseZeros()

File "Test1.py", line 7, in UseZeros return zeros(4)

NameError: global name 'zeros' is not defined

Is somebody able to help my understand why when calling this function, the IPython console no longer recognizes the method?

The only reference I can find to a similar problem was fixed in a previous release, and was different to what I'm experiencing.

The reason I need this to work is that I'm importing functions used by somebody else who has made extensive use of commands such as zeros, ones, sin, cos etc., and I don't want to have to redefine everything.

Thanks

Upvotes: 0

Views: 1260

Answers (2)

Carlos Cordoba
Carlos Cordoba

Reputation: 34156

(Spyder developer here) The option to Automatically load Pylab and NumPy modules is provided to facilitate interactive work in the console but it's not meant to write code in the Editor because that code won't run outside Spyder.

I'm afraid to tell you, but what your colleague has done is a very bad practice and, in my humble opinion, I think the best you can do is to instruct him/her to fix this problem.

There's nothing we can do on the Spyder side to fix/improve this situation because we're not willing to promote bad practices, sorry.

Upvotes: 0

Ben G.
Ben G.

Reputation: 306

As you use it, the import statement still has all functions and classes named within the module: import numpy, for instance, will allow you to access the ndarray class as numpy.ndarray. If you want to import a given class or function into the top-level namespace, you'll need to specifically import it:

from numpy import ndarray

And if you're writing something small and aren't worried about cluttering the namespace, you can do this:

from numpy import *

In your case, with Spyder's automatic imports it seems to only affect the __main__ level namespace, so you'll need to put proper import statements in any imported modules.

Upvotes: 1

Related Questions