[SciPy-User] (pas de sujet)

Chris Weisiger cweisiger at msg.ucsf.edu
Fri Apr 1 16:25:50 EDT 2011


On Fri, Apr 1, 2011 at 1:02 PM, Ralf Gommers <ralf.gommers at googlemail.com>wrote:

> On Fri, Apr 1, 2011 at 9:59 PM, Robert Kern <robert.kern at gmail.com> wrote:
> > On Fri, Apr 1, 2011 at 14:33, Christopher Barker <Chris.Barker at noaa.gov>
> wrote:
> >
> >> I'm not sure if:
> >>
> >> import scipy as sp
> >>
> >> is as common, but it seems reasonable to me.
> >
> > It's utterly useless since the scipy subpackages aren't imported along
> > with it. Don't do it.
>
> Our docs disagree:
> https://github.com/numpy/numpy/blob/master/doc/HOWTO_DOCUMENT.rst.txt
>
> It still saves a few characters writing "sp.linalg.xxx" instead of
> "scipy.linalg.xxx".
>

How valuable is saving a couple of characters, though? The quality of code
is not in how terse it is but in how effectively it communicates what it
wants to do, both to computers and to humans. Otherwise we'd always say "y"
instead of "why".

To respond cross-thread, as for why importing scipy doesn't grab all of the
sub-modules, but importing numpy does, check out these examples. % denotes a
Linux/OSX/Unix/etc. command line prompt, >>> denotes a Python REPL prompt.

% cat > foo.py
import bar
^D
% cat > bar.py
a = 10
^D
% python
>>> import foo
>>> foo.bar.a
10

In other words, because foo imports bar, bar is in foo's namespace; thus it
is valid to say "foo.bar" and to access contents of bar through foo. Compare
to this:

% mkdir foo
% touch foo/__init__.py
% cat > foo/bar.py
a = 10
^D
% python
>>> import foo
>>> foo.bar
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute 'bar'

In this case, "foo" is a package that contains many modules, but importing
the package does not actually import any of the modules in that package.
That __init__.py file created using the "touch" command is what allows you
to import foo in the first place, despite it not actually being a Python
module. The package is merely a container for other modules; if you want to
access those modules you have to specifically import them.

You could modify the contents of the __init__.py module to make it insert
things into the package namespace when you import the package, but for
whatever reason that's not done when you import scipy. My guess is that
scipy has so many diverse modules that any given program only uses a small
proportion of its capabilities. Importing the entire thing could seriously
slow down your program initialization; there's no need to pay that extra
cost. Meanwhile, numpy has a comparatively narrow scope, so it's not a huge
deal to just grab everything numpy can do when you do "import numpy".

-Chris
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.scipy.org/pipermail/scipy-user/attachments/20110401/e3950a6e/attachment.html>


More information about the SciPy-User mailing list