Skip to content Skip to sidebar Skip to footer

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

Solution 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.pydeffunc_in_b():
    print'this is B'# temp2.pyimport temp

deffunc_in_a():
    print'this is A'>>> import temp2
>>> temp2.func_in_a()
this is A
>>> temp2.temp.func_in_b()
this is B

Solution 2:

Import always imports the namespace of the module or package.

Package: A a directory containing __init__.pyModule: 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

Solution 3:

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.

Post a Comment for "In Python3, Does `import` Work Transitively?"