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.)
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
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With