Why does `import tensorflow` not raise error if `Package(s) is missing from the environment`?

0 views
Skip to first unread message

bill....@me.com

unread,
Apr 19, 2018, 12:24:31 AM4/19/18
to conda - Public
I have a short convenience script that reports the versions of certain packages in the current environment.  It includes a series of code snippets like this:

from platform import python_version


print('python: %s' % python_version())


if python_version() < '3.6':
    import_exception
= ImportError
else:
    import_exception
= ModuleNotFoundError


try:
   
import tensorflow
except import_exception:
   
print('tensorflow: not installed')
else:
   
print('tensorflow: %s' % tensorflow.__version__)

...


Typical output looks like this:

python: 3.6.5
tensorflow
: 1.5.0

...


I recently created a new environment with Python 3.4 and now the code doesn't work.  On investigation `import tensorflow` does not raise an error in this environment even though tensorflow is not installed.  To prove it, see the following console output:

(py34) BillsMacBookPro:~ billtubbs$ python
Python 3.4.5 | packaged by conda-forge | (default, Sep  8 2016, 14:36:28)
[GCC 4.2.1 Compatible Apple LLVM 6.0 (clang-600.0.54)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import tensorflow
>>> tensorflow.__version__
Traceback (most recent call last):
 
File "<stdin>", line 1, in <module>
AttributeError: 'module' object has no attribute '__version__'
>>> dir(tensorflow)
['__doc__', '__loader__', '__name__', '__package__', '__path__', '__spec__']
>>> exit()

(py34) BillsMacBookPro:~ billtubbs$ conda update tensorflow


PackageNotInstalledError: Package is not installed in prefix.
  prefix
: /Users/billtubbs/anaconda/envs/py34
 
package name: tensorflow





Can anyone explain this?  I expect 
import tensorflow
 to raise an error if `Package is not installed`.  If it doesn't raise an error, I expect tensorflow to import correctly.  Here it seems to have loaded an empty module called `tensorflow`





Thomas Holder

unread,
Apr 19, 2018, 5:32:40 AM4/19/18
to bill....@me.com, conda - Public
Could be a tensorflow.py file in your current directory. After the import, print tensorflow or tensorflow.__file__ will tell you were Python found the module.

(base) thomas@mbp:/tmp # touch tensorflow.py
(base) thomas@mbp:/tmp # python
>>> import tensorflow
>>> tensorflow.__file__
'tensorflow.py'
>>>

Thomas
--
Thomas Holder
PyMOL Principal Developer
Schrödinger, Inc.

Message has been deleted

bill....@me.com

unread,
Apr 19, 2018, 11:30:58 AM4/19/18
to conda - Public, bill....@me.com
Thanks Thomas.  You nailed it.  

tensorflow.__file__ does not work but there was a folder called 'tensorflow' with some files in it.  It was an accidental module!  (I found quite a few others actually).

Mental note: Don't name folders with Python module names...

thanks again.
Bill.

Reply all
Reply to author
Forward
0 new messages