4

I'm new here and am not 100% sure how to ask this question so I'll just dive right in. Should I be using import statements at the beginning of every function I write that import all of the various modules/functions I need for that function's scope? i.e.

def func1()
    import os.path
    print func(2)
    do something with os.path

def func2()
    import os.path
    do something with os.path

Will this increase memory overheads, or other overheads, or is the import statement just mapping a local name to an already loaded object? Is there are better way to do this? (Links to tutorials etc. most welcome. I've been looking for a while but can't find a good answer to this.)

miku
  • 181,842
  • 47
  • 306
  • 310
GlenS
  • 209
  • 3
  • 6
  • possible duplicate of [python import coding style](http://stackoverflow.com/questions/477096/python-import-coding-style) – S.Lott Jan 25 '11 at 03:43
  • 2
    @S. Lott. The topvoted answer to that question is technically wrong. I added a new on to it. The problem is that the timing technique used is very flawed and doesn't account for the difference in cost between accessing a local and accessing a global. – aaronasterling Jan 25 '11 at 04:41

2 Answers2

10

Usually all imports are placed at the beginning of the file. Importing a module in a function body will import a module in that scope only:

def f():
    import sys
    print 'f', sys.version_info

def g():
    print 'g', sys.version_info

if __name__ == '__main__':
    f() # will work
    g() # won't work, since sys hasn't been imported into this modules namespace
miku
  • 181,842
  • 47
  • 306
  • 310
7

The module will only be processed the first time it is imported; subsequent imports will only copy a reference to the local scope. It is however best style to import at the top of a module when possible; see PEP 8 for details.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • @GlenS: Learn PEP8. The sooner you do, the sooner your code will look right to other Python coders. – mlissner Mar 06 '12 at 06:07