Basic 'import' problem

John Roth newsgroups at jhrothjr.com
Sun Feb 8 04:17:28 CET 2004


"Frantisek Fuka" <fuka at fuxoft.cz> wrote in message
news:c03kmp$28u7$1 at ns.felk.cvut.cz...
> Diez B. Roggisch wrote:

> > But what you try is to already execute code from file in file2 _while_
> > importing file2 inside file, because you have statements on the
> > module-level - and that can't work. And I doubt that a language exists
> > where thats possible.

PL/1 at least.

> Yes, this seems logical. It looks like I have some fundamental problems
> with grasping the philosophy of Python...
>
> My application is started from base.py. This file imports many other
> files (modules) that do different stuff. Base.py references dozens of
> classes and functions in other modules. After a while, there comes a
> time when some of these modules need to reference some basic function
> inluded in base.py. Which means (I thought until now) that I have to
> include base.py in these files. Or not? Are you saying there is no
> chance of doing this? Let's forget "import" for now and please explain
> to me: Is there way to create a Python application consisting of several
> modules that can freely call and reference stuff in each other? From
> your answer it seems that the anwer is "no".

Actually, you can. There is a general principle that will
solve most of these problems, and a couple of emergency
(meaning completely non-obvious so the magic needs to
be thoroughly documented) procedures that will solve the rest.

The basic answer to this is to structure your modules in
layers as much as possible so that you avoid import loops.

The key to doing this is your class structure. The basic fact
is that your class structure cannot contain cycles. Your
module structure has to reflect your class inheritance
structure for this reason.

If you still have modules that require out of order
imports, you can solve some of these cases by putting
the out of order imports at the bottom of the modules
that need them.

If that doesn't work, then you need to do the out of order
imports in a second pass. There are two ways of doing
this.

One is to encapsulate the out of order imports in a module
level function and call that function from the driver after
all the modules have been imported; the other is simply
to slam the bindings for the out of order modules into the
modules that need them using setattr. I'd recommend
the first since it's easier to document.

John Roth

>
> -- 
>                                           Frantisek Fuka
> (yes, that IS my real name)
> (and it's pronounced "Fran-tjee-shek Foo-kah")
> ----------------------------------------------------
> My E-mail:   fuka at fuxoft.cz
> My Homepage: http://www.fuxoft.cz
> My ICQ:      2745855





More information about the Python-list mailing list