Anton Lahti
Anton Lahti

Reputation: 472

When porting python 2.5 to 3.X, how can I replace "from <module> import *"?

I've got a python 2.5 package with the following structure:

enter image description here

Config.py contains the following line:

from CommonDefines import *

Runnning this code in 3.7 gives the following exception:

File "../../.\ConfigLib\Config.py", line 7, in from CommonDefines import * ModuleNotFoundError: No module named 'CommonDefines'

Replacing that line with:

from .CommonDefines import *

... works in 3.7 but gives the following error in 2.5:

SyntaxError: 'import *' not allowed with 'from .'

Is there a way to write this line so that works in both 2.5 and 3.X?

EDIT:

The following doesn't work, since the second import triggers a syntax error in 2.5

try:
    from CommonDefines import *
except:
    from .CommonDefines import *

SyntaxError: 'import *' not allowed with 'from .'

Upvotes: 0

Views: 131

Answers (1)

kabanus
kabanus

Reputation: 25895

I would just use a proper name-by-name import, but this can be done in a hacky way, for your personal use, using exec:

try:
    from CommonDefines import *
except ModuleNotFoundError:
    exec('from .CommonDefines import *')

You can even swap them and catch the SyntaxError.

Upvotes: 1

Related Questions