I would like to know if it is possible to parameterized the way a module import one of its own module.
My problem is the following. I have a number of generic tensorflow functions, such as losses, that work with both version (1 and 2) of the API.
If the module is used with TF2, or with an old version of TF1, tensorflow needs to be imported like
import tensorflow as tf
However if I use TF 1.15, or if I want to use the version 1 of the API with TF2, tensorflow needs to be imported as
import tensorflow.compat.v1 as tf
tf.disable_v1_behavior()
So the way the import is done cannot be automatically deduced from the TF version, as TF2 can be used in TF1 "compatibility" mode.
Is there a way I can change the way the import is done in the module?
A hack that seems to work for modules that are directly imported:
import my_module
my_module.tf = tf
That forces the tf
module to be the same as the current one. However,
This could have invisible and hard-to-track side effects since tensorflow is imported with potentially different APIs requirement, this could mess up any global variable settings.
This works for modules imported directly, not for modules that are imported by other modules, unless the hack is propagated to all modules.