I want to use two Python libraries (Google's Cloud Library, and their Cloud SDK) in a single application, but they have conflicting names (they both use google
in their base import names and do not use relative imports internally). How can I use them in a single app?
Changing the library's code to use proper relative imports is not practical. Also, I know I can use virtualenv to access these libraries from separate python applications, but how do I access them from within the same python app?
Details of the Naming Conflict
Here are some of the details on the import. When I import a module from the Cloud Library (I run import google.cloud.datastore
), there is an exception about another import within that library:
>>> import libs.google.cloud.datastore
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "C:[ProjectDIR]libsgoogleclouddatastore\__init__.py", line 52, in <module>
from google.cloud.datastore.batch import Batch
ImportError: No module named cloud.datastore.batch
The library is trying to do an absolute import, rather than a relative one. The reason that the Google Cloud Library cannot import google.cloud.datastore.batch
is because google
is already defined in the SDK, there is a naming conflict:
>>> print google.__path__
['C:\Program Files (x86)\Google\Cloud SDK\google-cloud-sdk\platform\google_appengine\google']
Because the Cloud Library uses absolute imports, and the name google
is already defined in the SDK, then the import fails.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…