3

What is the right or PEP way to sort relative imports in python?

core/
    __init__.py
    forms.py
    models.py
    tests/
        __init__.py
        form_tests/
             __init__.py
            test_xpto.py
        login.py

If I am working with test_xpto.py and would like to import other files, what is the correct way:

from core.models import Person
from ..login import DefaultLogin
from ...forms import CustomerForm

or

from ...forms import CustomerForm
from ..login import DefaultLogin
from core.models import Person

or is not any of them?

martineau
  • 119,623
  • 25
  • 170
  • 301
Aipi
  • 2,076
  • 4
  • 18
  • 27
  • 1
    The official guidelines are here: https://www.python.org/dev/peps/pep-0008/#imports. Anything beyond those is up to you and your team to decide which you prefer. – jonrsharpe Jan 02 '18 at 14:12
  • See [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time). – martineau Jan 02 '18 at 14:49
  • 1
    Following the link jonsharpe gave, the bullet point after sorting import says: „Absolute imports are recommended, […]“, so just don't use relative imports and follow the guidelines in the first two bullet points. Then there is not much to decide any more. – BlackJack Jan 10 '18 at 14:15

1 Answers1

2

I got some answers to this question. According to with PEP 328 [1], has Guido pronounced saying that "relative imports will use leading dots. A single leading dot indicates a relative import, starting with the current package. Two or more leading dots give a relative import to the parent(s) of the current package, one level per dot after the first" [2]. Here's a sample package layout:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

Another good idea is isort (a Python utility / library to sort imports alphabetically, and automatically separated into sections) [3], which to sort the imports has followed an other pattern, which is used by big projects like Django [4]:

from __future__ import absolute_import

import os
import sys

from my_lib import Object, Object2, Object3
from third_party import (lib1, lib2, lib3, lib4, lib5, lib6, lib7, lib8, lib9,
                         lib10, lib11, lib12, lib13, lib14, lib15)

from . import moduleY
from ...sys import path
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from .moduleY import spam as ham 

[1] https://www.python.org/dev/peps/pep-0328/#guido-s-decision

[2] https://mail.python.org/pipermail/python-dev/2004-March/043739.html

[3] https://github.com/timothycrosley/isort

[4] https://github.com/timothycrosley/isort/wiki/Projects-Using-isort

Aipi
  • 2,076
  • 4
  • 18
  • 27