Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scope of imported modules/functions in Python

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

like image 727
GlenS Avatar asked Dec 03 '22 09:12

GlenS


2 Answers

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
like image 73
miku Avatar answered Dec 21 '22 19:12

miku


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.

like image 42
Ignacio Vazquez-Abrams Avatar answered Dec 21 '22 21:12

Ignacio Vazquez-Abrams