Using imported modules in more than one file
This question is a bit dumb but I have to know it. Is there any way to use imported modules inside other imported modules?
I mean, if I do this:
-main file-
import os
import othermodule
othermodule.a()
-othermodule-
def a():
return os.path.join('/', 'example') # Without reimporting the os module
The os module is not recognized by 开发者_StackOverflowthe file. Is there any way to "reuse" the os module?
There's no need to do that, Python only loads modules once (unless you unload them).
But if you really have a situation in which a module can't access the standard library (care to explain???), you can simply access the os
module within the main module (e.g. mainfile.os
, modules are just variables when imported into a module namespace).
If the os
module is already loaded, you can also access it with sys.modules["os"]
.
You have to put import os
in othermodule.py
as well (or instead, if "main file" doesn't need os itself). This is a feature; it means othermodule
doesn't have to care what junk is in "main file". Python will not read the files for os
twice, so don't worry about that.
If you need to get at the variables in the main file for some reason, you can do that with import __main__
, but it's considered a thing to be avoided.
If you need a module to be reread after it's already been imported, you probably should be using execfile
rather than import
.
Python only imports a module once. Any subsequent import calls, just access the existing module object.
精彩评论