[SciPy-user] Begginer's Problem

Robert Kern robert.kern@gmail....
Fri Oct 26 14:11:51 CDT 2007


Keith Suda-Cederquist wrote:
> Hi,
> 
> I started using SciPy recently (converted from Matlab) and am running
> into a problem.
> 
> I wrote my first script that uses PIL.Image module and several basic
> SciPy modules.  Within this script I declared functions that used
> functions in the PIL.Image and scipy modules, for example:
> 
> 
> #version1.py
> import scipy as S
> import PIL.Image as I
> 
> def imageopen(filename):
>     im1=I.open(filename)
>     ar1=S.ones((20,20))
>     ....
> 
> im2=imageopen(file2)
> 
> This worked out fine.  Then I decided it would be nice to move all the
> function definitions into a seperate file:
> 
> #split1.py
> def imageopen(filename):
>     im1=I.open(filename)
>     ar1=S.ones((20,20))
> 
> #split2.py
> import scipy as S
> import PIL.Image as I
> import split1
> 
> im2=imageopen(file2)
> 
> This new structure is giving me a lot of problems.  The usual error I
> get is that global name 'I' or 'S' is not defined.  I've searched quite
> a bit for a solution, but haven't figured it out yet. 
> 
> As far as I can tell the problem is related to the namespace belonging
> to particular modules.

Yes. Each module has its own namespace. When functions look up names which are
not provided in the argument list (e.g. I and S), they look them up in the
module in which they are defined, not the module in which they are called.

> I've been able to work around this by importing the scipy and PIL.Image
> modules all over the place (i.e. at the begging of split1.py and
> split2.py and inside the function).  However, this doesn't seem like the
> best way to handle this.
> 
> Any advice?

Generally speaking, you should import the things that you need at the top of the
module where you need them.

# correctsplit1.py
import scipy as S
import PIL.Image as I

def imageopen(filename):
    im1=I.open(filename)
    ar1=S.ones((20,20))


# correctsplit2.py
import correctsplit1

im2 = correctsplit1.imageopen('file2')


You may want to take questions like this to the Python tutor-list. That list is
more geared towards these kinds of general Python beginner questions.

  http://mail.python.org/mailman/listinfo/tutor

-- 
Robert Kern

"I have come to believe that the whole world is an enigma, a harmless enigma
 that is made terrible by our own mad attempt to interpret it as though it had
 an underlying truth."
  -- Umberto Eco


More information about the SciPy-user mailing list