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.)

2
  • possible duplicate of python import coding style Commented Jan 25, 2011 at 3: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. Commented Jan 25, 2011 at 4:41

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

1 Comment

I mean, is sys.modules per thread or per process or per computer?
8

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.

1 Comment

@GlenS: Learn PEP8. The sooner you do, the sooner your code will look right to other Python coders.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.