I came around this question and got quite disappointed by how the tensorflow developers try to make the tensorflow
directory appear as the actual package, whereas the actual package root is actually tensorflow/python
. By using a __init__.py
file of the form
from tensorflow.python import *
del python
they try to achieve this goal. This results in some inconsistent behaviour (at least so it seems to me) when working with the package, e.g.
import tensorflow.python # seems to work
tensorflow.python # AttributeError: no attribute 'python'
from tensorflow.python import Session # works as expected
tensorflow.python.Session # AttributeError: no attribute 'python'
from tensorflow import python # works as expected
tensorflow.nn # works as expected
import tensorflow.nn # ImportError: no module 'tensorflow.nn'
tensorflow.nn.tanh # works as expected
from tensorflow.nn import tanh # ImportError: no module 'tensorflow.nn'
Now, I was wondering whether/how it could be possible to avoid most/all of these issues to get a more consistent behaviour. The first set of inconsistencies could be easily resolved by not deleting the python
attribute. However, given that the goal would be to make the complete package appear as if it is a sub-package, this might not be entirely satisfactory.
To keep things simple, let's consider the following package structure
package/
__init__.py
api/
__init__.py
code.py
where package/api/code.py
looks something like
def a():
return 'alpha'
def b():
return 'bravo'
and package/api/__init__.py
would be
import package.api.code
would it be possible to create package/__init__.py
so that the following works
import package.api # ImportError: no module 'package.api'
package.api # AttributeError: no attribute 'api'
from package.api import code # ImportError: no module 'package.api'
package.api.code # AttributeError: no attribute 'api'
from package import api # ImportError: cannot import 'api'
package.code # works as expected
import package.code # works as above
package.code.a # works as expected
from package import a # correctly imports function a
I believe that the last four lines of code should give the expected result by adding to sys.modules
, but I do not seem to be able to find a way to make import package.api
fail.
Would anyone have an idea on how this could be done? Feel free to point me to use-cases that I am overlooking or should consider to achieve the above-mentioned goal.