Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 331
pyjamas Avatar asked Dec 02 '25 10:12

pyjamas


1 Answers

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.

like image 62
tdelaney Avatar answered Dec 04 '25 23:12

tdelaney



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!