Diez B. Roggisch wrote: [...] > The only valid reason for doing imports inside functions is if you > otherwise get into circular dependency hell, or have modules that need > some manipulation of the sys.path before they actually can be imported. > This is never true for system modules, and certainly to avoid if possible. > Well there is also the somewhat obscure point that an import of specific names inside a function makes them local, which *might* make a performance difference with tight loop nesting inside - though obviously the need for such will best be determined by benchmarking:
>>> def f1(): ... from os.path import join ... print join ... >>> from os.path import join >>> def f2(): ... print join ... >>> dis.dis(f1) 2 0 LOAD_CONST 1 (-1) 3 LOAD_CONST 2 (('join',)) 6 IMPORT_NAME 0 (os.path) 9 IMPORT_FROM 1 (join) 12 STORE_FAST 0 (join) 15 POP_TOP 3 16 LOAD_FAST 0 (join) 19 PRINT_ITEM 20 PRINT_NEWLINE 21 LOAD_CONST 0 (None) 24 RETURN_VALUE >>> dis.dis(f2) 2 0 LOAD_GLOBAL 0 (join) 3 PRINT_ITEM 4 PRINT_NEWLINE 5 LOAD_CONST 0 (None) 8 RETURN_VALUE >>> Not a major issue, just another aspect of the question ... and of course the OP should take the advice already given unless and until performance becomes a problem (since it usually won't). regards Steve -- Steve Holden +1 571 484 6266 +1 800 494 3119 Holden Web LLC http://www.holdenweb.com/ -- http://mail.python.org/mailman/listinfo/python-list