Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is Python implicit relative import

Tags:

python

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.

What Is Python Implicit Relative Import?

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?

Removed In Python3?

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'>

Why does pep-0008 suggest never use it?

like image 431
Cloud Avatar asked Feb 10 '18 03:02

Cloud


2 Answers

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
like image 194
John Zwinck Avatar answered Oct 19 '22 07:10

John Zwinck


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'>

like image 31
tardyp Avatar answered Oct 19 '22 07:10

tardyp