简体   繁体   中英

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 the 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 (eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM