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 a
Solution 1:
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:
deff():
import sys
print'f', sys.version_info
defg():
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
Solution 2:
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.
Post a Comment for "Scope Of Imported Modules/functions In Python"