python import multiple times

二次信任 提交于 2019-11-29 04:19:57

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

  • checks some global table if module is already imported
    • if module is not imported python imports it, creates module object and puts newly created module object to the global table
    • if module is imported python just gets module object
  • when python has module object it binds it to the name you chose
    • 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.

File module.py:

print("import is in progress")

def foo():
    pass

File main.py:

def foo():
    print("before importing module")
    import module
    module.foo()
    print("after importing module")

if __name__ == '__main__':
    foo()
    foo()

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!