gpt4 book ai didi

python - 进口到哪里?

转载 作者:行者123 更新时间:2023-11-28 21:22:23 25 4
gpt4 key购买 nike

我正在学习 Python,今天在编写一些代码时,我试图决定在何处放置 import 语句。

我几乎可以在任何地方放置 import 语句,但放置会如何影响性能、命名空间和其他我还不知道的东西?

最佳答案

官方的 GoodPractice 是将所有导入放在模块或脚本的开头,从标准 lib 模块/包开始,然后是第三方,然后是项目特定,参见 http://www.python.org/dev/peps/pep-0008/#imports

实际上,有时您不得不将导入推迟到函数中,作为循环依赖的快速但肮脏的解决方法(解决循环依赖的正确方法是在另一个模块中提取相关部分,但对于某些框架,您可能必须接受 Q&D 解决方法)。

恕我直言,出于“性能”原因推迟导入函数并不是一个好主意,但有时您不得不再次打破规则。

导入一个模块实际上意味着:

search the module_or_package in `sys.modules`
if not found:
search the module_or_package_source in `sys.path`
if not found:
raise an ImportError
create a `module` instance from the module_or_package_source
# -> imply executing the top-level source code, which may raise anything
store the `module` instance in `sys.modules`
bind the `module` name (or whatever name was imported from it) in the current namespace

wrt/什么是“当前命名空间”,实际上是这样的:import 语句被执行。这是包含所有三个示例的简单脚本:

try:
re
except NameError, e:
print "name 're' is not yet defined in the module's namespace"
print "module namespace : %s" % globals()

import re
print "name 're' is now defined in the module's namespace"
print "module namespace : %s" % globals()


def foo():
try:
os
except NameError, e:
print "name 'os' is not yet defined in the function's namespace"
print "function namespace : %s" % locals()
print "name 'os' is not defined in the module's namespace neither"
print "module namespace : %s" % globals()

import os
print "name 'os' is now defined in the function's namespace"
print "function namespace : %s" % locals()
print "name 'os' is still not defined in the module's namespace"
print "module namespace : %s" % globals()

foo()

print "After calling foo(), name 'os' is still not defined in the module's namespace"
print "module namespace : %s" % globals()

class Foo(object):
try:
os
except NameError, e:
print "name 'os' is not yet defined in the class namespace"
print "but we cannot inspect this namespace now so you have to take me on words"
print "but if you read the code you'll notice we can only get there if we have a NameError, so we have an indirect proof at least ;)"
print "name 'os' is not defined in the module's namespace neither obvisouly"
print "module namespace : %s" % globals()

import os
print "name 'os' is now defined in the class namespace"
print "we still cannot inspect this namespace now but wait..."
print "name 'os' is still not defined in the module's namespace neither"
print "module namespace : %s" % globals()

print "class namespace is now accessible via Foo.__dict__"
print "Foo.__dict__ is %s" % (Foo.__dict__)
print "'os' is now an attribute of Foo - Foo.os = %s" % Foo.os
print "name 'os' is still not defined in the module's namespace"
print "module namespace : %s" % globals()

关于python - 进口到哪里?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19292297/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com