[Tutor] Confusion regarding the 'from' statement

eryksun eryksun at gmail.com
Wed Aug 15 04:08:04 CEST 2012


On Tue, Aug 14, 2012 at 9:04 PM, Dave Angel <d at davea.name> wrote:
>
> 1) recursive imports.  If anybody has a non-trivial top-level code, or
> even certain class-initialization code, this can cause surprising errors.

Yes, it's a problem if you try to "from" import an object that hasn't
been defined yet  or use something that hasn't been properly
initialized. But AFAIK, just importing the current module won't
execute it twice unless it's running as __main__.  You get the
existing reference from sys.modules.

> 2) multiple imports under different names.  By importing the "same"
> module under the two names __main__ and mod1, you usually end up with
> two copies of stuff, and that can break a lot of implicit assumptions in
> working code.

I wasn't casting any judgment, but personally I agree it's a bad idea.
Without the "if" block the code executes twice, and everything gets
defined twice. If for some reason you need to import the main script
(for whatever reason, but the point is probably academic), import
__main__, not its module filename.


More information about the Tutor mailing list