How do I migrate from imp?

Right, it’s hard to understand subtle but risky consequences.

The recipe giving in What’s New In Python 3.12 — Python 3.13.0a2 documentation only reads the file, load it and execute it as a regular import. It doesn’t change sys.path.

2 Likes

hi Miro i have the same issue with my program did you get a solution yet for it, if there is imp for python 2 and importlib for python 3 how do i make my code compatible in both python 2 and python 3 i wnat to make it cross compatible, kindly give a reply, Thank You

Yes, I believe I have solved the case that bothered me, see my comment How do I migrate from imp? - #3 by hroncok

No, I did not have to solve it for Python 2, I am not interested in Python 2 and I will not be able to help you with that, sorry.

The same way as for anything else: check the value of sys.version_info in order to figure out whether the code is running under Python 2 or Python 3, and then inside an if statement, do the 2.x-specific stuff when it’s 2.x and the 3.x-specific stuff when it’s 3.x. That includes import statements, and you can also conditionally define functions. For example:

import sys
if sys.version_info.major == 2:
    import imp
    def load_module(name):
        # logic that uses Python 2.x's `imp` here
else:
    import importlib
    def load_module(name):
        # logic that uses Python 3.x's `importlib` here
1 Like

Or, even better: Write Python 3 code, but if it catches an exception due to a module not existing (probably because you’re on Python 2), it does other code.

import importlib
try:
    importlib.some_feature_you_need
except ImportError:
    equivalent_py2_code()

importlib.some_feature_you_need will raise AttributeError, not ImportError

Doh. This is what I get for whipping something up without knowing what I’m actually testing for, and therefore not being testable. Yes, that should be except AttributeError there. In any case, the same idea stands: test for the feature you want, and if it is absent, use a fallback.

Tip: If you use sys.version_info, then when the time comes you can use pyupgrade to automatically upgrade. For example, given:

import sys

if sys.version_info < (3,):
    import imp

    def load_module(name):
        # logic that uses Python 2.x's `imp` here
        ...
else:
    import importlib

    def load_module(name):
        # logic that uses Python 3.x's `importlib` here
        ...

Running pyupgrade 1.py --py38-plus gives:

import sys

import importlib

def load_module(name):
    # logic that uses Python 3.x's `importlib` here
    ...
2 Likes