Aipi
Aipi

Reputation: 2476

Sort order of relatives imports?

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?

Upvotes: 3

Views: 2210

Answers (1)

Aipi
Aipi

Reputation: 2476

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

Upvotes: 2

Related Questions