Can someone explain the difference between these?
from x import yfrom .x import yIt 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 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With