【问题标题】:I am using a large module in many of my files that takes some time to import. Will importing it in every file waste time?我在我的许多文件中使用了一个大型模块,需要一些时间才能导入。在每个文件中导入它会浪费时间吗?
【发布时间】:2023-01-21 12:18:19
【问题描述】:

我有一个需要一段时间才能导入的模块,我们称它为 big_module。该模块创建了我在其他文件中需要的几个变量。我在我的许多帮助程序文件中使用这个模块,称为 helper1、helper2 等...

我有一个导入每个帮助文件的主文件,所以我的文件看起来像这样:

# helper1.py

import big_module

def do_stuff1(input):
    # code that uses big_module
# helper2.py

import big_module

def do_stuff2(input):
    # code that uses big_module

等等帮助文件。然后我有我的主文件:

# main.py

import helper1
import helper2
# and so on

data1 = [some data]
data2 = helper1.do_stuff1(data1)
data3 = helper1.do_stuff2(data2)
# and so on

当我导入每个助手,然后每个助手随后导入 big_module 时,big_module 是否每次都重新运行,导致我浪费时间,或者 python 是否缓存它或其他东西以便它只运行一次?如果在多个文件中导入它确实浪费时间,有没有只导入一次的好方法?

【问题讨论】:

标签: python performance import


【解决方案1】:

不会。导入器会检查模块是否已经导入。如果是这样,您将获得对现有模块的引用,它不会被重新导入。您可以通过在模块级别向 .py 文件添加 print 来对此进行测试。您只会看到该打印一次。

如果 python 在每个import 上重新导入模块,那将是非常糟糕的。这意味着每个导入的每个导入都会看到不同的名称空间。如果导入的模块有全局变量,那么每次导入都会有一组不同的全局变量,并且很难保持对整个程序有效的状态。

【讨论】:

    猜你喜欢
    • 2015-03-13
    • 1970-01-01
    • 1970-01-01
    • 2021-09-18
    • 2018-01-16
    • 2014-04-20
    • 1970-01-01
    • 2019-11-14
    • 2022-12-10
    相关资源
    最近更新 更多