Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are sibling imports?

2to3 - Automated Python 2 to 3 code translation - Fixers - import note that:

Detects sibling imports and converts them to relative imports.

like image 815
acgtyrant Avatar asked Oct 17 '22 12:10

acgtyrant


1 Answers

Sibling import is not a terminus technicus. In the context of your question it means:

  • Importing a file from the same directory (so the importing file and the imported one are siblings relative to the file system), or

  • Importing a module (modules) from such a file.


Note:

The problem rose from the small difference between Python 2 and Python 3 import systems, but let first compare file system paths with packages/modules paths used in the import or from ... import statements:

+---+--------------------------+-------------------------+
|   |    In the File system    |   In the Python import  |
+---+--------------------------+-------------------------+
| 1 | /doc/excel               |  doc.excel              | <--- absolute
| 2 |   excel (we are in /doc) |   excel (we are in doc) | <--- ???
| 3 | ./excel (we are in /doc) |  .excel (we are in doc) | <--- relative
+---+--------------------------+-------------------------+

The substantial difference is this:

In file systems we always recognize the absolute path as a path which begins with / (or something similar), so cases 2 and 3 in the previous table have the same meaning - both are relative paths.

But in the Python import system, case 2 means: search for excel in the current module (i.e in doc), but if it is not found, consider it as the top-level module. And this can make problems.

The 2to3.py analyses such ambiguous (case 2's) imports, tries to determine which of them are siblings ones (in the meaning mentioned at top of this answer), and converts them to be unambiguously relative ones (i. e. into case 3's).

(Case 3 is always unambiguous - leading . means the relative path, i. e. the module doc.excel).

like image 109
MarianD Avatar answered Oct 20 '22 11:10

MarianD