简体   繁体   中英

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? ie

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM