202

I'm looking over the code for Python's multiprocessing module, and it contains this line:

from ._multiprocessing import win32, Connection, PipeConnection

instead of

from _multiprocessing import win32, Connection, PipeConnection

the subtle difference being the period before _multiprocessing. What does that mean? Why the period?

Vlad the Impala
  • 15,572
  • 16
  • 81
  • 124
  • 3
    It's called relative import: http://docs.python.org/tutorial/modules.html – Aillyn Sep 02 '11 at 06:17
  • 1
    Without the `.`, if you had a file `_multiprocessing.py` for some indecipherable reason next to your main script, `multiprocessing` would break. With the `.`, it ensures it gets its own module. – Chris Morgan Sep 02 '11 at 06:19
  • If a `.` refers to peer modules, why would the documentation say to use a `.` when that multiprocessing module should be part of the regular sys.path libraries? Does the question and Chris' clarification mix them up or am I not understanding? Appreciate the help. – rfii Jul 16 '20 at 23:13
  • Another Question (now closed) with alternative, good answers: https://stackoverflow.com/questions/22511792/python-from-dotpackage-import-syntax – Gabriel Staples Feb 10 '21 at 18:13

3 Answers3

167

That's the syntax for explicit relative imports. It means import from the current package.

Boris Verkhovskiy
  • 14,854
  • 11
  • 100
  • 103
Keith
  • 42,110
  • 11
  • 57
  • 76
  • 43
    What defines what the "current package" is? – fraxture Dec 03 '15 at 22:31
  • 7
    It should say *from where the importing package is*. It basically means the current namespace or package directory. – Keith Dec 05 '15 at 19:05
  • 2
    Thanks, I think I know what you mean. Just to be clear, would you mind providing an example? – fraxture Dec 12 '15 at 12:05
  • 11
    You can do things like: `from . import peermodule` `from .. import parentpackagemodule` – Keith Dec 15 '15 at 05:24
  • Can you use three dots to represent a grandparentpackagemodule? from ... import grandparentmodule – bmc Jan 19 '19 at 21:26
  • Here's where the real crux and explanation of _relative imports_ begins to get explained in the link you provided: https://www.python.org/dev/peps/pep-0328/#guido-s-decision. – Gabriel Staples Feb 10 '21 at 18:06
  • Here's another good explanation from another (now closed) question: https://stackoverflow.com/a/22511861/4561887. – Gabriel Staples Feb 10 '21 at 18:07
34

default one dot in your current folder, when you want to go parent folder you can do like this, my python version 3.6.3

enter image description here

Gin
  • 629
  • 5
  • 9
24

The dot in the module name is used for relative module import (see here and here, section 6.4.2).

You can use more than one dot, referring not to the curent package but its parent(s). This should only be used within packages, in the main module one should always use absolute module names.

Martin Gunia
  • 1,091
  • 8
  • 12