1

Hello I am using Django with Python and I don't understand this :

from . import views

I would like to know what I am importing when I type that.

Thank you for your explanations

Bruce Peter
  • 31
  • 1
  • 4
  • 1
    You import the `view.py` file in the same directory as the file where the `import` statement is located. – Willem Van Onsem Apr 21 '19 at 10:01
  • 2
    @WillemVanOnsem: Describing it like that propagates the misconception that relative imports are about directories, when they're really about packages. There are very important differences; for example, if I have files `a.py` and `b.py` in the same directory and I run `python a.py`, `a.py` can't do `from . import b`, because `a.py` and `b.py` aren't submodules of a common package. – user2357112 Apr 21 '19 at 10:59
  • 1
    Possible duplicate of [from . import XXXX](https://stackoverflow.com/questions/7417353/from-import-xxxx) – Gino Mempin Apr 21 '19 at 11:33

3 Answers3

2

You can import files, modules and packages using relative or absolute paths.

Take a look at this project:

-- project_folder
    --project_name
        ──settings.py
        ──init.py
        ──urls.py
        ──wsgi.py
    --app1
        ──__init__.py
        ── models.py
        ── views.py
        ── admin.py
        -- package1_folder
            ── hello_world.py

A relative import is used to retrieve a resource relative to the current path you are on.

So if you are currently working inside app1 -> views.py and you want to import hello_world.py to your views you can use . to specify a relative import to the current file you are working on.

So to import hello_world.py we could use from .package1_folder import hello_world.

If you just specify from . import models you are importing the models.py resource from the current folder you are on(app1).

An absolute import on the other hand is used to import a resource from anywhere in the project using the full path.

For example, you can use from app1.package1_folder import hello_world anywhere in your project and you will successfully import the file.

danny bee
  • 840
  • 6
  • 19
1

You import views.py from the location of the python script that calls import statment.

mlotz
  • 130
  • 3
  • No. If you write `import views`, you specify an "absolute path", so it is the `views.py` in the `PYTHON_PATH`, the `.` is a *relative path*. – Willem Van Onsem Apr 21 '19 at 10:09
1

import from same directory , ".." mean import from upper directory

biswa1991
  • 530
  • 3
  • 8