Best practices with import?

chris liechti cliechti at mails.ch
Sat Jul 28 23:27:36 EDT 2001


Erik Max Francis <max at alcyone.com> wrote in 
news:3B6369D4.671C1870 at alcyone.com:

>      def main():
>          import sys # here's the only place that sys gets used
>          lines = sys.readlines()
>          # do something with lines ...
> 
>      if __name__ == '__main__':
>          main()
> 
> I'm really not sure what the value would be in deleting the module after
> you're through with it, except perhaps to clean up namespaces, which I
> wouldn't think would be useful if, say, it were defined in the scope of
> a function.
> 

i think the module gets deleted anyway because its imported into the local 
namespace of the function and that gets deleted after the function returns.

there is a performance argument against "import"ing in functions:
if this fu is called in a loop the module gets imported and deleted every 
time. importing it at top level doesn't need that and hence the loop runs 
faster.

on the other hand for debugging functionality that is later removed i find 
it appropriate to import only there where its needed. and for modules that 
are only used in "__name__ == '__main__'" section, it's also very suitable.


and yes there is a "cache" see here:
--cut--------file: mymod.py
print "mymod"
--cut--------test code:
import mymod
mymod.a = 1

def fu():
    import mymod
    print "fu"
    print dir(mymod)

fu()
--cut-------this is the output:
mymod
fu
['__builtins__', '__doc__', '__file__', '__name__', 'a']
--cut-------

as you can see the main module alters "mymod" and this change can be seen 
in the function where it is imported another time.

-- 
chris <cliechti at mails.ch>




More information about the Python-list mailing list