gpt4 book ai didi

Python - 导入 if

转载 作者:IT老高 更新时间:2023-10-28 20:51:04 26 4
gpt4 key购买 nike

我为 urllib (python3) 编写了一个小包装器。在if中导入模块是否正确安全

if self.response_encoding == 'gzip':
import gzip

我没有找到任何关于此代码的 PEP。但是,这让我很困扰。

最佳答案

Python 标准库使用它,所以它绝对是正确和安全的。见 os module source举个很好的例子:

if 'posix' in _names:
name = 'posix'
linesep = '\n'
from posix import *
try:
from posix import _exit
except ImportError:
pass
import posixpath as path
import posix
__all__.extend(_get_exports_list(posix))
del posix

在 python 中有条件地导入模块是很常见的。除了 if,您通常还会看到 try:/except ImportError: 组合:

try:
from subprocess import check_output
except ImportError:
# Python 2.6 and before
def check_output(*popenargs, **kwargs):
from subprocess import Popen
if 'stdout' in kwargs:
raise ValueError('stdout argument not allowed, it will be '
'overridden.')
process = Popen(stdout=PIPE, *popenargs, **kwargs)
output, unused_err = process.communicate()
retcode = process.poll()
if retcode:
cmd = kwargs.get("args")
if cmd is None:
cmd = popenargs[0]
raise CalledProcessError(retcode, cmd)
return output

在这里,我们基本上使用了一个道德上的等价物 if 测试:如果你可以导入 check_output,那么就这样做,否则在这里定义完整的函数。

导入语句只是将外部代码重新绑定(bind)到本地名称。在这方面,使用 if 控制流来控制导入与在 if 语句中分配变量没有什么不同。您需要确保最终不会在未定义任何一种方式的情况下使用该名称。

关于Python - 导入 if,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12860841/

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