简体   繁体   中英

Import module, that import another module. Python

I was curious what happens when we import a module that in turn imports another module. So I create two modules: module1 and module2.

module1:

import random
print(random.randint(0,10))
print("module1 work")

module2:

import module1
print("module2 work")

When I run module2 it give me this output:

1
module1 work
module2 work

So, I decided that I did indeed import random , when I imported module1 . But when I type in the Shell print(random.randint(0,10)) it throws a NameError: name 'random' is not defined . So random wasn't imported from module1 . But in this case why did module2 print 1 , and didn't throw the same error as the Shell?

Each module has its own scope (or namespace, if that terminology is more familiar to you). If you want to access random from module2 , you need to import it in module2 . The interpreter shares the scope of the module you execute, so only variables declared in the global namespace of that module will be accessible. If you want to access random from the interpreter having only imported module2 , you'll need to specify module1.random .

Alternatively, you can replace import module1 with from module1 import * . That will copy over everything, including the reference to random . So random will be accessible globally.

It is because you are not actually importing random into the shell, instead just the file that contains the module.

We can use an existing module as an example, for example tkinter which opens with:

import enum
import sys

They import into the Tkinter module but when you import Tkinter they don't come with it.

To put it is as simply as possible your module1 has random imported, but imporing module1 will not also import random

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