简体   繁体   中英

In Python3, does `import` work transitively?

In Python3, does import work transitively?

For example, if a module contains import A , and the module for A contains import B , then does the module import B indirectly?

Compared to other languages:

  • In Java, some said that import doesn't work transitively, see https://stackoverflow.com/a/46677664 .

  • in C, include does work transitively. For example, if a file contains #include "Ah" , and Ah contains #include "Bh" , then the file also includes Bh indirectly.

How do Python's import , Java's import, and C's include` work under the hook to have differences?

Thanks.

When you're importing a module to your namespace, Python creates a module namespace. This goes recursively; when you import A , it will import B and if it fails you'll get an error. Otherwise it will be accessible through AB

# temp.py
def func_in_b():
    print 'this is B'

# temp2.py
import temp

def func_in_a():
    print 'this is A'

>>> import temp2
>>> temp2.func_in_a()
this is A
>>> temp2.temp.func_in_b()
this is B

Import always imports the namespace of the module or package.

Package : A a directory containing __init__.py Module : A file with the extension .py

Modules

If you have a file named a.py with the content:

x=2

File named b.py with the content:

import a
y=3

In the interpreter it will be

>>> import b
>>> b.y
3

>>> b.a.x
2

Packages

Packages are behaving differently(maybe not so intuitive, if you come from Java), having a directory structure like:

+ mypackage
+-__init__.py
+-test.py

A import of the package mypackage wont import the module test.py but only evaluate __init__.py :

>>> import mypackage
>>> mypackage.test # will fail

C/C++'s #include works on preprocessor level. Java and Python doesn't have a preprocessor. They are more smart, their VMs know about any modules you can import at runtime. Imports there is a way to avoid conflicts of names. In Java you may not use imports at all but then you should define full class names every time (eg java.util.List instean of just List ). Almost the same for Python.

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