简体   繁体   English

Python中导入的模块/函数的范围

[英]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? 我是新来的,并不是100%肯定如何提出这个问题,所以我只是潜入。我应该在我编写的每个函数的开头使用import语句,导入我需要的所有各种模块/函数该功能的范围? 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? 这会增加内存开销或其他开销,还是只是将本地名称映射到已加载对象的import语句? 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: 在函数体中import模块将仅import该范围内的模块:

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. 有关详细信息,请参阅PEP 8。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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