pyjamas
pyjamas

Reputation: 5367

Python 'from x import y' vs 'from .x import y'

Can someone explain the difference between these?

  1. from x import y
  2. from .x import y

It seems like #1 will import from x only if x is in PYTHONPATH or is in the current working directory, but I don't see any reference of this syntax in the docs https://docs.python.org/3/reference/import.html

Upvotes: 4

Views: 1204

Answers (2)

tdelaney
tdelaney

Reputation: 77337

Python has multiple ways to find and import modules as detailed in the Finders and Loaders section of the import documentation. Finders use distribution specific directories, frozen modules, paths in PYTHONPATH and usually the directory where the script is loaded. You can get a list of paths in sys.path and alsosys.modules.keys().

When handling from x import y python checks if "x" is already imported, and then goes through the list of finders to see which one pipes up with a solution for a module named "x". Next, it checks whether "x" has a variable called "y". If not, it tries to import a module "y" relative to the "x" it already found.

More details of the syntax and semantics of import can be found in The import statement subsection of the Simple Statements section.

The second example only works for modules in packages. The periods tell how far up the package hierarchy to go before descending back down named packages. One dot means current module directory, and each dot moves downwards towards the base.

Upvotes: 1

Zain Patel
Zain Patel

Reputation: 1033

These fall under "relative imports" which are located in section 5.7 of the documentation you've linked: https://docs.python.org/3/reference/import.html#package-relative-imports

You can also look at PEP-382 for the rationale on relative imports and their uses.

Upvotes: 0

Related Questions