0

I'm reading PEP328:

The python-dev community chose absolute imports as the default because they're the more common use case and because absolute imports can provide all the functionality of relative (intra-package) imports -- albeit at the cost of difficulty when renaming package pieces higher up in the hierarchy or when moving one package inside another.

Can anyone explain the part I highlighted?

NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64

2 Answers2

1

You can find an explanation of absolute vs. relative imports here.

Basically, absolute imports use the full path of the module starting from the project's root. This is useful when you're importing modules from an outside package.

When you're importing modules from within your current package, you can theoretically use a relative path. For example, assume your project has packages pkg1 and pkg2. Lets say you want to import a module from pkg1 into pkg2. You can do it like so

from ..pkg1 import module1

The advantage of this is that you can avoid changing your imports even when you update your project structure, provided that the relative paths between the imports are preserved (for example moving all packages into some new parent package). Despite this convenience, the community chose to use absolute imports as the default since they provide all the functionally which relative imports provide.

Roman Tz
  • 89
  • 4
  • So how to absolute import `pkg1.module1` in `pkg2.py`, given that the two files (`pkg1.py`, `pkg2.py`) are in the sibling folders? – NeoZoom.lua Sep 07 '21 at 10:57
  • You need to specify the full path of module1 from the root folder of the project without regard to the path of pkg2, just like you would do in an external module not within the current project. – Roman Tz Sep 07 '21 at 14:43
0

because absolute imports can provide all the functionality of relative (intra-package) imports

Given:

Project
 \-- A -- pkg1 -- B
        L pkg2 -- C

Then in B.py(, you can imagine that there is a main.py next to A, so the following relative import works):

from ..pkg2.C import c_func

which can be transformed to:

from A.pkg2.C import c_func

Now if I rename A to H, then:

no change in relative form:

from ..pkg2.C import c_func

in absolute form:

from H.pkg2.C import c_func         # One change.
from H.pkg1.B import b_func         # One more change.
# Many more imports are waiting your changes.
NeoZoom.lua
  • 2,269
  • 4
  • 30
  • 64