How do I migrate from imp?

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