On 2007-05-30 11:32:05 -0400, Mike Schinkel wrote:
> 
> anders pearson wrote:
> > Without looking too closely at the rest, the error is because 
> > you've imported the module, but haven't imported Make or the 
> > other classes from the model. So you need to either do: 
> > 
> >    from model import Make,Model,Year,ModelYear
> 
> Thank! For a newbie, can you explain why "import mode" didn't bring in all
> of those classes?  I've been reading Python in a Nutshell and I thought it
> would...

I'm not sure I can give you a better explanation than just "that's the
semantics of python's import statement".  It's designed the way it is
to avoid namespace clashes while still making things as convenient as
you want to. 

Make, Model, etc. are all defined inside the 'model' module (actually,
probably inside 'yourapp.model', if it's a standard TG app, but you
set up your sys.path so 'model' is available directly) so they need to
be brought into the namespace of your script somehow to be used. So
the options are basically: 

    1) import model
    2) from model import Make,Model,Year,ModelYear
    3) from model import *

the first only imports the 'model' module at it's top level so you
then need to explicitly access any classes/functions/etc within it
explicitly as 'model.Whatever'. 

The second explicitly imports a couple classes from 'model' into the
current namespace so you can use them later without fully qualifying
them. 

The third imports everything from the 'model' module into the current
namespace. So you could then use Make, or Model, or anything else
directly. You usually want to avoid doing that though since it
increases the chances of namespace collisions if you're importing from
multiple modules or there happens to be something in 'model' with the
same name as in the current namespace. It also makes code harder to
read since you can't backtrack as easily and figure out where things
are defined (a task that's otherwise very straightforward in
Python). It's convenient though and common for things like SQLObject
where you need to import a lot of functions and classes for it to be
useful. 

The standard docs are pretty clear I think: 

    http://docs.python.org/tut/node8.html

Python's import mechanism takes a bit of getting used to depending on
where you're coming from but it's quite elegant once you understand
it. (Mostly. sys.path stuff can get a little hairy.)

-- 
anders pearson : http://www.columbia.edu/~anders/
   C C N M T L : http://www.ccnmtl.columbia.edu/
        weblog : http://thraxil.org/

Attachment: pgpjKwOYg1LK7.pgp
Description: PGP signature

Reply via email to