[Zope-dev] Coding style clarifications

Martijn Faassen faassen at startifact.com
Fri Feb 20 11:00:08 EST 2009


Hi there,

> Names exported to a containing package cause circular import problems
> whether or not from imports are used.  I've seen from imports make this
> worse. I believe you've seen cases where they make it better.  I think the
> only way to avoid this is to use a deferred import mechanism such as
> zope.deferredimport. (This is one of the few batteries I actually wish
> Python included.)

A bunch of us spent quite a bit of time diving into this issue at the
sprint a few weeks ago here. It's quite mystifying but enough to reach
some conclusions.

in foo.baz.py:

import foo.bar

will trigger for some reason a more complete import of 'foo' so that
the attribute 'bar' can be accessed.

foo's __init_.py cannot do this then:

from foo.bar input whatever

If instead baz.py contains:

from foo import bar

The problem will not arise. If instead you do:

import foo.bar as bar

which you'd think was the semantic equivalent, it *will*.

The main take-home message was that the import mechanics of Python are
rather surprising in operation here and it's very hard to reason about
it. It has something to do with 'foo'" having to be more initialized
during importing than in the other case. I do know that the pattern of
'from' imports in a package's module will allow me to write a
__init__.py assembling a namespace from sub-modules, while the pattern
of "import foo.bar" in a package's module will give circular import
related errors. "foo" in the latter case will have to be a more
complete object.

Regards,

Martijn


More information about the Zope-Dev mailing list