20
>import tensorflow

>import tensorflow.contrib

>tensorflow.contrib

module 'tensorflow.contrib' from 'D:\\ProgramData\\Anaconda3\\lib\\site-packages\\tensorflow\\contrib\\__init__.py'

>import tensorflow.python

>tensorflow.python

Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AttributeError: module 'tensorflow' has no attribute 'python'

As you can see, I run this code in a cmd(win 10). Both "import tensorflow.contrib" and "import tensorflow.python" are OK, but commands "tensorflow.contrib" and "tensorflow.python" are different. One returns a directory and the other returns AttributeError.

Does anyone have a clue why?

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
cmjdxy
  • 396
  • 1
  • 2
  • 15

3 Answers3

16

tensorflow.__init__() explicitly deletes its reference to the tensorflow.python module after importing everything from it.

The reason for that is to provide access to the submodules contained in the python package in the top-level tensorflow namespace. A few things from the tensorflow.core package are also imported and made available in the tensorflow namespace.

I think that the idea is not to import tensorflow.python directly. Those classes, objects, and submodules of python that are intended to be used by applications are made available simply by import tensorflow.

jss367
  • 4,759
  • 14
  • 54
  • 76
mhawke
  • 84,695
  • 9
  • 117
  • 138
  • Thank you for the response, I think this sounds reasonable. – cmjdxy Nov 15 '17 at 12:15
  • @mhawke The thing that bothers me is that the statement `import tensorflow.python` does not lead to the `AttributeError`. Any chance you have an explanation for that? – Mr Tsjolder from codidact Nov 15 '17 at 13:25
  • 1
    @MrTsjolder: the import succeeds without `AttributeError` because the package exists. Why should it fail? The thing is that when `import tensorflow.python` is executed, `tensorflow` is imported first, _before_ `tensorflow.python`. `tensorflow.__init__.py` explicitly imports what it wants from `tensorflow.python` then deletes the reference to `python` so it is not in the namespace of the importing code. Because `tensorflow.python` was already imported, it is not imported again, so the deleted reference remains deleted. – mhawke Nov 16 '17 at 00:02
  • so where does this lead the import of tensorflow.python.keras? – ben26941 Mar 04 '19 at 11:43
2

You can import tensorflow.python the following way:

from tensorflow import python as tf_python
Ark-kun
  • 6,358
  • 2
  • 34
  • 70
-4

Worked for me by using the following import line:

from tensorflow.python import keras

Cheers!

Patrick W
  • 1,485
  • 4
  • 19
  • 27