0

I am going through Flask source. I see a lot of statements like

from . import x

I am not Python novice so I understand what from and import keywords do. But what is from . ? Could someone explain with an example?

Edit1: My question is about just import . not import .module

Edit2: how is from . import x different from from import x

Prasad Honavar
  • 107
  • 1
  • 2
  • 10
  • 1
    Possible duplicate of [Python "from \[dot\]package import ..." syntax](https://stackoverflow.com/questions/22511792/python-from-dotpackage-import-syntax) – Wright Feb 10 '18 at 05:58
  • 1
    Sort of a duplicate, but `from .` (just the dot, not something like `from .models`) appears different enough that it warrants its own question. – Chris Martin Feb 10 '18 at 05:59
  • 1
    @Wright That question is about `.modulename`, not `.` by itself. – Barmar Feb 10 '18 at 06:00
  • There's got to be a duplicate of this already, though. – Barmar Feb 10 '18 at 06:00
  • 4
    Possible duplicate of [from . import XXXX](https://stackoverflow.com/questions/7417353/from-import-xxxx) – Barmar Feb 10 '18 at 06:02
  • 1
    ``from .`` is a way of doing ``relative addressing``. More info at this link : https://docs.python.org/3/tutorial/modules.html?highlight=relative%20import#intra-package-references – PaW Feb 10 '18 at 06:04
  • @PW how is `from . import x` different from from `import x` ? – Prasad Honavar Feb 10 '18 at 06:13
  • 1
    The ``.`` will force it to look for the module in the current package. For example, if you had a ``from . import json``, in your case it will import from flask's ``json`` module (flask.json) instead of the default python ``json`` module. – PaW Feb 10 '18 at 06:19
  • That clears my question. thanks @PW – Prasad Honavar Feb 10 '18 at 06:25

2 Answers2

2

It is an example of Intra-package references in python. (Check out section 6.4.2 on https://docs.python.org/3/tutorial/modules.html)

When writing packages in python, from . import X is used to import sub-packages from the parent class, i.e. importing a sibling class. The . is only used to refer to the parent package in the relative path.

However, you can always import parent package without using the . in import statement, by using the name of the parent package name/path. Using . is just a handy shortcut.

1

from . import x

Will import locally to that script.

Python includes a json library so

from . import json

Is used to avoid importing the standard library json and instead import a local python module

jamylak
  • 128,818
  • 30
  • 231
  • 230