evan54
evan54

Reputation: 3733

Why am I getting NameError: name 'array' is not defined

I'm using spyder and have written the following class:

class Ray:

    def __init__(self, r, p, k):

        if r.shape == (3,):
            self.r = r
        if p.shape == (3,):
            self.p = p
        if k.shape == (3,):
            self.k = k

r = array(range(3))
p = array(range(3))
k = array(range(3))

It is stored in /home/user/workspace/spyder/project and the console working directory is that one. In the console I can run an array(range(3)) and it returns an array with values 0,1,2. However when doing

import ray

I get the following error

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "ray.py", line 8, in <module>
    class Ray:
  File "ray.py", line 20, in ray
    r = array(range(3));
NameError: name 'array' is not defined

EDIT:

by default spyder has the following behaviour, don't really understand why array() works by default I thought it was only part of numpy.

import numpy as np  # NumPy (multidimensional arrays, linear algebra, ...)
import scipy as sp  # SciPy (signal and image processing library)

import matplotlib as mpl         # Matplotlib (2D/3D plotting library)
import matplotlib.pyplot as plt  # Matplotlib's pyplot: MATLAB-like syntax
from mayavi import mlab          # 3D plotting functions
from pylab import *              # Matplotlib's pylab interface
ion()                            # Turned on Matplotlib's interactive mode

Within Spyder, this intepreter also provides:
    * special commands (e.g. %ls, %pwd, %clear)
    * system commands, i.e. all commands starting with '!' are subprocessed
      (e.g. !dir on Windows or !ls on Linux, and so on)

Upvotes: 1

Views: 23542

Answers (1)

Eric O. Lebigot
Eric O. Lebigot

Reputation: 94475

You need from numpy import array.

This is done for you by the Spyder console. But in a program, you must do the necessary imports; the advantage is that your program can be run by people who do not have Spyder, for instance.

I am not sure of what Spyder imports for you by default. array might be imported through from pylab import * or equivalently through from numpy import *. If you want to directly copy code from the Spyder console to a program, you might need from numpy import * or even from pylab import *. It is officially not recommended to do this in a program, though, as this pollutes the program's namespace; doing import numpy as np and then np.array(…) is customary.

Upvotes: 13

Related Questions