【问题标题】:Can I import a module in the middle of a code?我可以在代码中间导入模块吗?
【发布时间】:2018-07-26 21:55:14
【问题描述】:

我知道有 discussions 讨论这个话题。我的情况可能有点“特殊”。我的代码bar.py 需要使用一个模块,比如说foobar.py 的一般用法是这样的:

python bar.py --threads 3 --dir jjj

问题是加载foo 需要很长时间(~40s),所以我想在加载之前检查参数的正确性。将import foo 放在代码后面而不是顶部是否有意义?

【问题讨论】:

  • 你尝试的时候发生了什么?

标签: python


【解决方案1】:

是的,在 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)

现在,在您的“特殊”情况下,是的,最好延迟导入直到参数被解析和验证。在文件中间导入的唯一缺点是组织,但在有意义的情况下这是必要的权衡。

【讨论】:

    【解决方案2】:

    从技术上讲,您可以在任何您喜欢的地方导入模块,但请注意,它将成为 本地 名称;如果在类或函数的中间导入,那么它将在该范围内,而不是在全局(模块)范围内。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-07-26
      • 2013-01-08
      • 2017-08-20
      • 1970-01-01
      • 1970-01-01
      • 2019-07-30
      • 2016-07-30
      • 1970-01-01
      相关资源
      最近更新 更多