python - Changes in import statement python3 -
i don't understand following pep-0404
in python 3, implicit relative imports within packages no longer available - absolute imports , explicit relative imports supported. in addition, star imports (e.g. x import *) permitted in module level code.
what relative import? in other places star import allowed in python2? please explain examples.
relative import happens whenever importing package relative current script/package.
consider following tree example:
mypkg ├── base.py └── derived.py
now, derived.py
requires base.py
. in python 2, (in derived.py
):
from base import basething
python 3 no longer supports since it's not explicit whether want 'relative' or 'absolute' base
. in other words, if there python package named base
installed in system, you'd wrong one.
instead requires use explicit imports explicitly specify location of module on path-alike basis. derived.py
like:
from .base import basething
the leading .
says 'import base
module directory'; in other words, .base
maps ./base.py
.
similarly, there ..
prefix goes directory hierarchy ../
(with ..mod
mapping ../mod.py
), , ...
goes 2 levels (../../mod.py
) , on.
please note relative paths listed above relative directory current module (derived.py
) resides in, not current working directory.
@brenbarn has explained star import case. completeness, have same ;).
for example, need use few math
functions use them in single function. in python 2 permitted semi-lazy:
def sin_degrees(x): math import * return sin(degrees(x))
note triggers warning in python 2:
a.py:1: syntaxwarning: import * allowed @ module level def sin_degrees(x):
in modern python 2 code should , in python 3 have either:
def sin_degrees(x): math import sin, degrees return sin(degrees(x))
or:
from math import * def sin_degrees(x): return sin(degrees(x))
Comments
Post a Comment