Sunday, 29 March 2015

from . import stuff in python

I came across this piece of code in a Django App

    from . import views

The dot is used to specify explicit relative imports, which tells the python interpreter to import views from the current pacage.

This change was added in PEP-0328.

You can also use more than one dot to more deeper into the package heirarchy, for instance

package/
    __init__.py
    subpackage1/
        __init__.py
        moduleX.py
        moduleY.py
    subpackage2/
        __init__.py
        moduleZ.py
    moduleA.py
Assuming that the current file is either moduleX.py or subpackage1/__init__.py , following are correct usages of this syntax:

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




Post a Comment