[Tutor] From Numpy Import *
Dinesh B Vadhia
dineshbvadhia at hotmail.com
Fri Nov 9 00:56:06 CET 2007
Thank-you! It is important for us to avoid potential code conflicts and so we'll standardize on the import <package name> syntax.
On a related note:
We are using both NumPy and SciPy. Consider the example y = Ax where A is a sparse matrix. If A is qualified as a scipy object then do y and x also have to be scipy objects or can they be numpy objects?
Dinesh
----- Original Message -----
From: Michael H. Goldwasser
To: Dinesh B Vadhia
Cc: tutor at python.org
Sent: Wednesday, November 07, 2007 5:37 PM
Subject: [Tutor] From Numpy Import *
On Wednesday November 7, 2007, Dinesh B Vadhia wrote:
> Hello! The standard Python practice for importing modules is, for example:
>
> import sys
> import os
> etc.
>
> In NumPy (and SciPy) the 'book' suggests using:
>
> from numpy import *
> from scipy import *
>
> However, when I instead use 'import numpy' it causes all sorts of errors in my existing code.
The issue is the following. The numpy module includes many definitions, for
example a class named array. When you use the syntax,
from numpy import *
That takes all definitions from the module and places them into your
current namespace. At this point, it would be fine to use a command
such as
values = array([1.0, 2.0, 3.0])
which instantiates a (numpy) array.
If you instead use the syntax
import numpy
things brings that module as a whole into your namespace, but to
access definitions from that module you have to give a qualified
name, for example as
values = numpy.array([1.0, 2.0, 3.0])
You cannot simply use the word array as in the first scenario. This
would explain why your existing code would no longer work with the
change.
> What do you suggest?
The advantage of the "from numpy import *" syntax is mostly
convenience. However, the better style is "import numpy" precisely
becuase it does not automatically introduce many other definitions
into your current namespace.
If you were using some other package that also defined an "array" and
then you were to use the "from numpy import *", the new definition
would override the other definition. The use of qualified names helps
to avoid these collisions and makes clear where those definitions are
coming from.
With regard,
Michael
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20071108/8b01dc8a/attachment.htm
More information about the Tutor
mailing list