Reason for not allowing import twice but allowing reload()

alien2utoo at gmail.com alien2utoo at gmail.com
Sun Mar 6 03:20:02 EST 2016


Based on the input from members, and my subsequent reading the textbook/tutorials, let
me summarize my understanding of "why subsequent imports of same module are designed to be effect-less".

1. Imports are costly affair, as it involves
 - finding the module's file
 - compile it to byte code (if needed)
 - run the module's code to build the objects it defines.

2a. Quoting from "Learning Python: Mark Lutz" : In Python, cross-file module linking
    is not resolved until such import statements are **executed at runtime**.

import being a statement, can come anywhere a statement can, so a module can be
selectively imported depending upon the conditions at runtime.

2b. Inter-dependencies between modules: For example, A (main module) imports B, C, D
    and E. B again imports C and E, D imports B and C.

If import statements are processed entirely from scratch each time, it would amount
to lot of **redundant (and costly)** work.

Secondly there could be dangerous? side-effects of reprocessing imports from scratch.

Let us say, in above example, module B does some initialization of variables, or
things like resetting a file for further work during the session. These variables and
file are updated during the course of execution of A.

Much later via some conditional path, module B is imported again, and BOOM (were
import processed from scratch again).

In this case - we are respecting that every import of a module should give same
picture (assuming it is not modified across two different invocation during the
program execution).

An argument here could be: to code module B in such a way that those initializations
don't happen again, but just once - check before resetting etc. during the import.
But wouldn't that violate the *same picture* requirement?

Probably my example is not that perfect.



More information about the Python-list mailing list