In PEP 8 -- Style Guide for Python Code
Explicit relative imports are an acceptable alternative to absolute imports
Implicit relative imports should never be used and have been removed in Python3.
Implicit import is a algorithm
Search up from current package directory until the ultimate package parent gets hit.
-- From https://www.python.org/dev/peps/pep-0328/#rationale-for-relative-imports
Can someone explain it in detail?
python2 -c 'import csv; print(csv)'
<module 'csv' from '/usr/local/Cellar/python/2.7.13/Frameworks/Python.framework/Versions/2.7/lib/python2.7/csv.pyc'>
$ touch csv.py
$ python2 -c 'import csv; print(csv)'
<module 'csv' from 'csv.pyc'>
# In python3 still search from current package
$ python3 -c 'import csv; print(csv)'
<module 'csv' from '/path_to/csv.py'>
When you say:
import foo
Python 2 would look first in the caller's directory. Python 3 will not do that, and will only find foo
in the usual places like sys.path
(PYTHONPATH
, site-packages
, etc.).
This means if you're writing a package that supports Python 3, you should say this inside your package:
import mypkg.foo
Or use an explicit relative import:
from . import foo
in python3, your code only works because python3 adds the parent directory of the python module you call to the sys.path
it won't work if you use submodule and use implicit relative import from submodule.
mkdir -p smod
touch smod/csv.py
echo 'import csv; print(csv)' > smod/__init__.py
python3 -c 'import smod; print(smod)'
<module 'csv' from '</path/to>/lib/python3.9/csv.py'>
<module 'smod' from '/<home>/test/smod/__init__.py'>
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