Is this a valid use of 'import'?

Terry Reedy tjreedy at udel.edu
Tue Jul 22 13:26:15 EDT 2008



Frank Millman wrote:

> I know that when a module is imported the first time, it is
> 'executed'. This normally entails setting up constants, classes,
> functions, etc, that you want to make available to the importer.

And every time thereafter, the module code is not executed*.  So module 
code should only be code you want executed exactly once, on first 
import, and never again.

> In this particular case, when it is executed, it does a whole lot
> more. It reads in some parameters, establishes a socket connection,
> starts a thread, and starts monitoring the socket using select.select.
> It also exposes some functions that disguise the complexity of reading
> from and writing to the socket.

What if you want to open another connection, because you want a second, 
or because you closed the first (to help the server while the client 
does something else) or because the connection got dropped because the 
server timed it out or because of network congestion or whatever?

tjr

*Python2 has a built-in reload function, but in 3.0 it is removed 
because it almost never did what people wanted or expected and thus lead 
to surprising bugs.  You can delete a module from sys.modules and 
re-import it, but the module object and those it created will not 
disappear as long as there are other references to them.




More information about the Python-list mailing list