Circular import problem

bvdp bob at mellowood.ca
Sat Jul 14 19:44:05 CEST 2007


> > But, I still don't understand how python can access a function in a
> > file I have NOT included. In this case, to get things to work, I DO
> > NOT "import MMA.grooves" but later in the module I access a function
> > with "xx=MMA.grooves.somefunc()" and it finds the function, and works
> > just fine. It shouldn't work.
>
> That depends a bit on what is "MMA" and what is "grooves".
> MMA.grooves means "look for an attribute named grooves inside MMA". If MMA
> is a module, and MMA.grooves is a class/function defined inside the
> module, you don't need to import it before using it.
> But if MMA is a package, and MMA.grooves is a module inside that package,
> you need to import it first (unless MMA/__init__.py does that already)

In this case (and I should have been more clear) MMA is a package and
grooves is a module. It is working now, but before I moved other
imports around I was able to do the following:

 1. NOT include MMA.gooves,
 2. call the function MMA.grooves.somefunc()

and have it work. The point I was trying to make was that something in
my imports was causing the namespace to contain MMA.grooves.* when it
hadn't been imported in that module.

I suspect that my reordering effected some initialization of modules,
probably the creation of some classes. But that is a guess.

I've just used an empty __init__.py file. I will have to read up a bit
more on packages and see what advantage there is to import in that.

> > I have tried to delay the import, and that does work. But, from a
> > stylistic view I really to like to have all my imports at the top of
> > the module. Maybe some old assembler/C habits on my part.
>
> Sure, it's considered good style.

Which is considered good style? Loading at the top or loading when
needed?






More information about the Python-list mailing list