0

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

2 Answers 2

1

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
Sign up to request clarification or add additional context in comments.

Comments

1

The standard way is to not check the version but rather if the characteristic you are interested in is present. This way, you are not tied to a particlar version line and provider. E.g.:

if hasattr(module, 'foo'):
    # new version
else:
    # old version


try:
    import tkinter
except ImportError:
    import Tkinter as tkinter


ironpython = hasattr(Exception, 'clsException')    #the feature that interests us
<...>
if ironpython: import System

Sometimes though, checking for the feature is hard, so to check for version is much easier:

# ABI config variables are introduced in PEP 425
if sys.version_info[:2] < (3, 2):
    import warnings
    warnings.filterwarnings('ignore', r"Config variable '[^']+' is unset, "
                                      r"Python ABI tag may be incorrect",
                            category=RuntimeWarning)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.