Search code examples
pythonversioning

Using import with multiple versions of a module with different structure


Suppose a function was moved from one module to another between package versions, e.g. as in this question, and we'd like to support both versions in our client code, that imports this function. Should we simply check the version and compare it to the first major version where change happened, or is there a more elegant solution? I.e. something like this (in the context of the linked question):

import tensorflow
from packaging import version
if version.parse(tensorflow.__version__) >= version.parse("1.12"):
    from tensorflow.python.training import device_util
else:
    from tensorflow.python.distribute import device_util

Solution

  • Use an exception handler catching ImportError.

    try:
        from tensorflow.python.training import device_util
    except ImportError:
        # This method was moved in tensorflow 1.12
        from tensorflow.python.distribute import device_util