In Python3, does `import` work transitively?

匿名 (未验证) 提交于 2019-12-03 09:02:45

问题:

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 "A.h", and A.h contains #include "B.h", then the file also includes B.h indirectly.

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

Thanks.

回答1:

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 A.B

# 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 


回答2:

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 (e.g. java.util.List instean of just List). Almost the same for Python.



回答3:

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 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!