python导入多次 [英] python import multiple times

查看:185
本文介绍了python导入多次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想这是一个普遍的问题,如果没有张贴在正确的地方,很抱歉。

I suppose this is a general question so sorry if not posted in the right place.

比如说,我有一个函数 a 导入 os 。如果我要多次从另一个文件调用此函数,我假设导入也会多次执行?有没有办法只导入模块,如果它不存在?

Say for instance, I have a function a which imports os. If I was to call this function from another file multiple times I am assuming that the import would be done multiple times as well? Is there a way to only import the module if its not already present?

基本上,我有一个类调用从各种文件导入的多个函数,而不是导入整个文件我认为导入这个函数会更容易,但现在我想知道从长远来看我是否会让自己头疼过多。

Basically, I have a class which calls multiple functions imported from various files, instead of importing the whole file I thought it would be easier to import just the function but now I am wondering if I am going to give myself headaches in the long run with excess imports.

推荐答案

在python文档中描述时python看到一些import语句它执行以下操作:

As described in python documentation, when python see some import statement it does the following things:


  • 检查一些全局表是否已导入模块


    • 如果未导入模块,则python导入它,创建模块对象并将新创建的模块对象放入全局表中

    • 如果导入模块,则python刚刚获取模块对象


    • 如果它是 import foo 模块名称 foo foo

    • 如果它是 import foo as bar 模块名称 foo bar

    • 如果来自foo import bar as baz python在模块 foo中找到函数(或其他) bar 并将此函数绑定到名称 baz

    • if it was import foo name for module foo will be foo
    • if it was import foo as bar name for module foo will be bar
    • if it was from foo import bar as baz python finds function (or whatever) bar in module foo and will bind this function to name baz

    所以每个模块只导入一次。

    So each module is imported only one time.

    为了更好地理解导入机制,我建议创建玩具示例。

    To better understand import mechanics I would suggest to create toy example.

    文件 module.py

    print("import is in progress")
    
    def foo():
        pass
    

    文件 main.py

    def foo():
        print("before importing module")
        import module
        module.foo()
        print("after importing module")
    
    if __name__ == '__main__':
        foo()
        foo()
    

    将上面的文件放在同一目录中。当导入 module.py 时,它会打印导入正在进行。当您启动 main.py 时,它将尝试多次导入模块,但输出将为:

    Put above files to the same directory. When module.py is being imported it prints import is in progress. When you launch main.py it will try to import module several times but the output will be:

    before importing module
    import is in progress
    after importing module
    before importing module
    after importing module
    

    因此导入只发生一次。您可以调整此玩具示例以检查您感兴趣的案例。

    So import really happens only once. You can adjust this toy example to check cases that are interesting to you.

    这篇关于python导入多次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆