Recalling import in module

孤街浪徒 提交于 2020-01-15 01:49:12

问题


I'm still learning python and after playing around with pygame I noticed I'm re-importing things in modules I'm importing that I've already imported.

import pygame

For instance I have some classes in a separate file, but I must also import pygame into that file too for them to work. Does it actually import the code twice? Will it slow down my program? Or does it just pull the same import from cache, but if it does that, why would I need to import it again?

Is there anything like (load) in lisp that just pulls in the code like it is part of the main file?

Thank You


回答1:


Subsequent imports pull the cached module reference from sys.modules. You need to import in order to add the module to the current namespace/scope.




回答2:


When Python imports a module, it first checks the module registry (sys.modules) to see if the module is already imported. If that’s the case, Python uses the existing module object as is.

  • http://effbot.org/zone/import-confusion.htm



回答3:


Got it!
Okay I found what I was looking for. I just found it clunky to have to re-import code I already imported, especially when the file isn't a library or something, just split up code. found it here: http://norvig.com/python-lisp.html

execfile("file.py")

Answers my problem perfectly. It parses a file and executes the code in it. Using it I was able to take out the extra import statements and it runs perfectly :D



来源:https://stackoverflow.com/questions/2936027/recalling-import-in-module

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