2.1.1 global weirds

Alex Martelli aleaxit at yahoo.com
Sun Aug 12 11:29:26 EDT 2001


"Robin Becker" <robin at jessikat.fsnet.co.uk> wrote in message
news:6Def3XA5vnd7Ewrz at jessikat.fsnet.co.uk...
    ...
> >The special module name 'half-breaks' circularity, just enough to
> >let you run unit tests decently.
>
> well if the name were kept the same and my special magic __main__
> variable worked that wouldn't be required, so we would have clarity and
> functionality.

Nope.  If, say, a is "being imported" (sys.modules['a'] is defined),
then an import a becomes a no-op (except for binding local name a
to sys.modules['a']).  So if a imports b and vice versa, b cannot
yet use anything from a -- the body of a need not have finished
executing, so def and class statements may not have run.  But if
a is running as main, then b's "import a" is NOT a no-operation --
because there's a sys.modules['__main__'] but NOT yet a
sys.modules['a'] -- so b CAN use a's stuff after import a IF
b has been imported from the main module.  Clearer now?

> However, I feel that the real underlying problem is that
> it is possible for the same module level code to have two different
> module names and that this is the real ambiguity.

Anybody who wants to do circular imports must be prepared to
deal with such trifles -- it's really a tiny part of the complexity
he's setting himself up for when doing circular imports.  Having
a given module-level code TWICE is a MUST to enable unit-tests
in the presence of circularity; if not for the main script (doing the
unit-tests) being under a different name, you'd have to explicitly
copy the source file -- so you'd have the same module level code
again under two names, but with a LOT of work to accomplish it.
Python saves you that work, even if you're so misguided as to
design with circular imports (it can't save you from OTHER sides
of the complexity you set up for yourself, of course).

> There's probably some reason for allowing A.B and B to have the same
> module source and be different modules, but I don't know what it is. The

I've been trying to explain it for the last zillion posts in this
thread, and I get the strong impression that I'm not getting
through, so maybe you STILL don't know it despite by best
efforts -- so, I give up.

There are other potential motivations, such as letting a module x
import __main__ in order for x to be importable from different
scripts with different/overridden behavior, but I wouldn't call
that a good design practice (though as a q&d hack it may well
be useful once in a blue moon).

> same is true for the __main__ module it's probably too difficult to work
> out what the true module name should be.

??? what do you mean by "too difficult"?  The Python interpreter
knows the filename it's loading, except when running from standard
input of course.


Alex






More information about the Python-list mailing list