94

Looking through a Django tutorial I saw the following syntax:

from .models import Recipe, Ingredient, Instruction

Can someone explain how the .models works / what it does exactly? Usually I have:

from myapp.models import

How does it work without the myapp part in front of .models?

wobbily_col
  • 10,271
  • 11
  • 56
  • 78

2 Answers2

126

Possible duplicate: What does a . in an import statement in Python mean?

The . is a shortcut that tells it to search in the current package before the rest of the PYTHONPATH. So, if a same-named module Recipe exists somewhere else in your PYTHONPATH, it won't be loaded.

Gabriel Staples
  • 22,024
  • 5
  • 133
  • 166
Sudeep Juvekar
  • 4,598
  • 2
  • 30
  • 35
  • 7
    @Hack-R - 2 dots represent parent directory. – Bhindi Feb 20 '17 at 06:59
  • @Bhindi oh thank you! I can't believe I didn't realize that – Hack-R Feb 20 '17 at 14:39
  • 8
    python checks for current directory first,so what is the use of . ? – ns94 Jul 21 '17 at 14:20
  • 6
    @shadow0359 the "current" directory is not always the directory in which the script resides. The script could be imported into another script in a different directory. – Aswin Jan 19 '18 at 00:08
  • These are called _relative imports_. See the full and official explanation here: https://www.python.org/dev/peps/pep-0328/#guido-s-decision, and the other answer here: https://stackoverflow.com/a/7279834/4561887. – Gabriel Staples Feb 10 '21 at 18:04
1

In addition of Sudeep Juvekar, this question is also related to manage.py's behavior.

In django-admin.py and manage.py:

It puts your project’s package on sys.path.

Zulu
  • 7,776
  • 9
  • 44
  • 55