简体   繁体   中英

Python import package in module behavior

I have a behavioral question about Python. Coming from the C background, I understand that modules are not the same as header files.

Here are two scripts:

Module1.py

#!/usr/bin/python3
import urllib

Driver.py

#!/usr/bin/python3
import module1

The behavior I expected at first was for urllib to be imported along with module1 inside the driver. However, this is not the behavior that I am experiencing. Is it correct to put

#!/usr/bin/python3
import urllib
import module1

Or does that cause urllib to be imported twice?

I read in the documentation that the I can do something like

from module1 import urllib

but that seems to be too much writing

The behavior I expected at first was for urllib to be imported along with module1 inside the driver.

Why should it? You've imported urllib inside the namespace (module dictionary) of module1 and not in that of Driver .

urllib is imported but, in module1 , try:

import Driver
Driver.module1.urllib

and see that no NameError s are raised, urllib is there.

does that cause urllib to be imported twice?

No, Python will see urllib has already been imported (by peeking inside sys.modules ) and just create an entry for urllib in the namespace or Driver .

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