[Tutor] import statements in functions?

Marcus Goldfish magoldfish at gmail.com
Mon Mar 21 22:53:54 CET 2005


Is there a convention to be considered for deciding if import
statements should be included in a function body?  For example, which
of these two module layouts would be preferable:

     # --- MyModule1.py -----
     import foo1, foo2, foo3
     import foo_special
    
     # several coherent functions here

     def specialFunction():
          doSomethingSpecial()

or the "embedded import" version:

     # --- MyModule2.py -----
     import foo1, foo2, foo3
     import foo_rare
    
     # several coherent functions here

     def specialFunction():
          import foo_special
          doSomethingSpecial()

Also, does the choice have any impact on performance/space/etc.?  And
will the import function get called each time (and possibly ignored)
in the second version?

The reason I consider the second form is that the module foo_special
is only used by the code in specialFunction(), and detracts (IMHO)
from understanding the rest of the code in the module.

Thanks,
Marcus


More information about the Tutor mailing list