0

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,

  1. 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.

  2. This works for modules imported directly, not for modules that are imported by other modules, unless the hack is propagated to all modules.

user209974
  • 1,737
  • 2
  • 15
  • 31

1 Answers1

0

I use, as in https://stackoverflow.com/a/32965521/2069610:

>>> import pkg_resources
>>> pkg_resources.get_distribution("tensorflow").version
'XX.XX'

Another idea would be to grep:

$ pip freeze | grep tensorflow
tensorflow==XX.XX

are you using pip or conda? This might also offer couple of different options, based on the output of conda list or so..

Based on that, you could use one or the other import...

lhd
  • 436
  • 4
  • 16
  • The thing is that this cannot depend on the version of the tf package. I could have TF 2.1 installed yet use the v1 API. – user209974 Apr 17 '20 at 13:35