109

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?

0

2 Answers 2

145

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.

5
  • 10
    @Hack-R - 2 dots represent parent directory.
    – Bhindi
    Feb 20, 2017 at 6:59
  • @Bhindi oh thank you! I can't believe I didn't realize that
    – Hack-R
    Feb 20, 2017 at 14:39
  • 10
    python checks for current directory first,so what is the use of . ?
    – ns15
    Jul 21, 2017 at 14:20
  • 8
    @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, 2018 at 0:08
  • 1
    These are called relative imports. See the full and official explanation here: python.org/dev/peps/pep-0328/#guido-s-decision, and the other answer here: stackoverflow.com/a/7279834/4561887. Feb 10, 2021 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.

Not the answer you're looking for? Browse other questions tagged or ask your own question.