[Tutor] proper import syntax

Kirby Urner urnerk@qwest.net
Sat, 08 Sep 2001 12:46:29 -0700


>
>Did I miss anything?
>
>- Andrei

I think you gave a pretty good answer.

When it comes to others reading code, there are always
comments and __doc__ strings etc., so you have the ability
to give more clues if your think a readership might be
appreciative.

Sometimes what we're importing are packages, not just
modules, as defined by some __init__.py in the package
directory.  These may be written in such a way that
'from package import *' gives you a small set of classes
you'd like to have top-level.  If that might be confusing
for readers, just say something in comments.

Booting to IDLE:

  >>> dir()
  ['__builtins__', '__doc__', '__name__']

This shows an initially "empty" shell namespace.  Now
I bring in a package:

  >>> from mathobjects import *
  >>> dir()
  ['Fraction', 'Matrix', 'Poly', 'Sqmatrix', '__builtins__',
  '__doc__', '__name__', 'deriv', 'polynomial', 'pyfraction',
  'simplematrix']

Some new tools have been added.  But it's not clear which
of these might be variables, which might be modules etc.
If I'm in shell mode and want to do some introspection,
I could go:

  >>> for i in dir():  eval(i)

This spits back some useful information about what's in
my bag:

  <class mathobjects.pyfraction.Fraction at 00B49B4C>
  <class mathobjects.simplematrix.Matrix at 00B4029C>
  <class mathobjects.polynomial.Poly at 00B4C41C>
  <class mathobjects.simplematrix.Sqmatrix at 00B41D6C>
  <module '__builtin__' (built-in)>
  '__main__'
  <function deriv at 00B4D66C>
  'i'
  <module 'mathobjects.polynomial' from
  'D:\PROGRAM  FILES\PYTHON21\ocn\mathobjects\polynomial.pyc'>
  <module 'mathobjects.pyfraction' from
  'D:\PROGRAM FILES\PYTHON21\ocn\mathobjects\pyfraction.pyc'>
  <module 'mathobjects.simplematrix' from
  'D:\PROGRAM FILES\PYTHON21\ocn\mathobjects\simplematrix.pyc'>

I see that I've imported some classes and modules.

I might further analyze a class:

  >>> dir(Fraction)
  ['__abs__', '__add__', '__div__', '__doc__', '__eq__',
  '__float__', '__gt__', '__init__', '__lt__', '__module__',
  '__mul__', '__neg__', '__pow__', '__radd__', '__rdiv__',
  '__repr__', '__rmul__', '__rsub__', '__sub__', 'denom',
  'fformat', 'float', 'list', 'mkfract', 'numer', 'recip',
  'simplify']

Hmmm....  looks like I can add, subtract Fraction objects.

The author (me) doesn't seem to have put in a lot of helpful
__doc__ strings, so I'm not sure how to initialize a Fraction
object.  I can look at the code, if I have Python source (not
always the case).

...  not disagreeing with anything you typed, just riffing
on how a user might probe and prod imported stuff, to figure
out what's going on.  In this sense, I'm inspired by your
excellent model:  always try to look at what you're doing
from the point of view of some reader who doesn't have the
benefit of your intimate knowledge of whatever it is you're
doing (good advice for life-at-large, I'd add).

Kirby