简体   繁体   中英

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

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 also sys.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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM