[Chicago] Import question

Martin Maney maney at two14.net
Tue Dec 23 03:48:55 CET 2008

On Mon, Dec 22, 2008 at 06:58:42PM -0600, Daniel Griffin wrote:
> I am having a problem with imports. I have 2 files, 1 which sets up
> SQLAlchemy and maps the object and the other which imports the first so that
> it can get a database connection.
> Example
> file obj
> import db
> class obj:
> file db
> from obj import obj
> mapper(obj....)
> Session() = scoped_session()
> python
> from obj import obj
> can't find obj
> I hope this makes sense, its twisting my brain around. Does anyone know what
> I am doing wrong?

>>> from obj import obj

This requires module obj to be imported, of course.  During that
import, before class obj is defined, module db has to be imported. 
during *that* import, an attempt is made to import obj and access the
class obj... which doesn't yet exist.  Exception time.

It's not that you can't import recursively, the problem is that you
have to consider what you can actually access at the time it recurses. 
If class obj can be defined without referring to db, the easy fix would
be to move that import below the class obj definition.  If you really
cannot define class obj without having access to stuff in db which in
turn requires the ability to instantiate class obj, there is no hope
for this design.

Think of it this way: how would you write it if there were only the
obj.py file, and it had to contain everythig from both files as they
are now.  How could you order things so that it would work that way?

We reject kings, presidents, and voting.
We believe in rough consensus
and running code. -- David Clarke

More information about the Chicago mailing list