我知道已经讨论了有关此主题的讨论。我的案子可能有点"特别"。我的代码bar.py
需要使用一个模块,例如,foo
。bar.py
的一般用法是这样的:
python bar.py --threads 3 --dir jjj
问题是加载foo
需要很长时间(〜40s(,因此我想在加载之前检查参数的正确性。在稍后将import foo
放在代码中而不是顶部?
您可以从技术上导入一个模块,但请注意,它将成为 local 名称;如果在类或功能的中间导入,则将仅在中,而不是全局(模块(范围。
是的,在Python中,您可以在Python文件中的任何地方导入模块。但是,范围很重要。例如,如果您在全球范围内import foo
,则模块在全球可用,例如:
import foo
# you can use `foo` here
def main():
# you can use `foo` here too
# ...
但是,如果您在类或功能的内部导入,则该模块仅在该范围内可用。例如:
def main():
import foo
# `foo` is available here (scope of `foo`)
def validate_something():
# `foo` is available here because `validate_something` has a child scope of the `main` function's scope
def parse_args():
# `foo` is not available here (scope of `parse_args`)
# `foo` is also not available here (the global scope)
现在,在您的"特殊"案例中,是的,将导入延迟直到解析和验证参数是理想的选择。在文件中间进口的唯一缺点是组织,但这是有意义的方案中的必要权衡。