Changes in Import Statement Python3

Changes in import statement python3

Relative import happens whenever you are importing a package relative to the current script/package.

Consider the following tree for example:

mypkg
├── base.py
└── derived.py

Now, your derived.py requires something from base.py. In Python 2, you could do it like this (in derived.py):

from base import BaseThing

Python 3 no longer supports that since it's not explicit whether you want the 'relative' or 'absolute' base. In other words, if there was a Python package named base installed in the system, you'd get the wrong one.

Instead it requires you to use explicit imports which explicitly specify location of a module on a path-alike basis. Your derived.py would look like:

from .base import BaseThing

The leading . says 'import base from module directory'; in other words, .base maps to ./base.py.

Similarly, there is .. prefix which goes up the directory hierarchy like ../ (with ..mod mapping to ../mod.py), and then ... which goes two levels up (../../mod.py) and so on.

Please however note that the relative paths listed above were relative to directory where current module (derived.py) resides in, not the current working directory.


@BrenBarn has already explained the star import case. For completeness, I will have to say the same ;).

For example, you need to use a few math functions but you use them only in a single function. In Python 2 you were permitted to be semi-lazy:

def sin_degrees(x):
from math import *
return sin(degrees(x))

Note that it already triggers a warning in Python 2:

a.py:1: SyntaxWarning: import * only allowed at module level
def sin_degrees(x):

In modern Python 2 code you should and in Python 3 you have to do either:

def sin_degrees(x):
from math import sin, degrees
return sin(degrees(x))

or:

from math import *

def sin_degrees(x):
return sin(degrees(x))

change in import in python3

Inside of __init__.py, if you change

from TestModule import TestFun

to

from .TestModule import TestFun

You'll get the expected behavior.

See: PEP 328 (sections regarding relative imports using leading dots).

How to make an import statement work on both python 2 and python 3

For your imports, you can do the following:

import sys
if sys.version_info[0] < 3:
#import your py2 packages
else:
#import your py3 packages

Settings file reference is not found

Due to ambiguity absolute import was removed in python3 for such use case. (This explains it very well: Changes in import statement python3)

You can use relative import for this use case maybe - https://docs.python.org/3/reference/import.html#package-relative-imports



Related Topics



Leave a reply



Submit