Is this a valid use of 'import'?
mccredie at gmail.com
Tue Jul 22 17:27:07 CEST 2008
On Jul 22, 8:12 am, Frank Millman <fr... at chagford.com> wrote:
> Hi all
> I am familiar enough with the normal use of 'import'. However, I have
> found a use for it which seems effective, but I have not seen it used
> like this before, so I am not sure if there are any downsides.
> 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.
> 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.
> This enables me to write a 'client' program that look like this -
> from Utils.client import *
> cust = getRecord(
> print cust
> As you can see, it makes writing a client program very easy.
> Are there any problems with this approach?
> Frank Millman
If it works for you that is great. That module however probably isn't
very readable or easy to modify however. Also, you are hiding a lot of
the complexity in a place where it isn't expected. Chances are it
would be easy to do the same thing at the class level instead of the
module level by putting all of that setup into the __init__ method of
a class, which is the proper place to do that sort of thing. Making
your code look something like this:
from utils.client import Connection
conn = Connection(userid='frank', pwd='')
cust = conn.getRecord(
Without seeing your other code it is difficult to know what the issues
might be. In general, this is what classes are for.
More information about the Python-list