I am using Python 2.6 and have the Facebook API installed as a python package (under /usr/lib64/python2.6/site-packages/facebook/...) which means, it is available with a plain import facebook
or from facebook import ...
.
This works well, as long as there is no name clash. For example, in my project, I try to import the Facebook API in my code at project.facebook with
from .facebook import GraphAPI
From my understanding, this should work becau开发者_运维技巧se the dot explicitly tells Python to look for the package one step up in the package hierachy and not try to import the project.facebook package it is already parsing.
However, it does not work:
Could not import project.views. Error was: cannot import name GraphAPI
project.views is another source code file that includes project.facebook (I am using Django but I'm not sure whether it has got something to do with that).
I know, I could just rename my source file or use from __future__ import absolute_import
(that works just fine) but I consider both to be workarounds.
Is there any reason why the from .facebook import ...
does not work?
Update:
Here is the output of ls -R in my workspace directory (which contains proj as the only project).
The following content is located under /home/chris/dev/workspace/, whereas the Facebook Python API is globally installed (in /usr/lib64/python2.6/site-packages/facebook/...).
./proj/templates: ...
./proj/templates: ...> ./proj: README src static templates
./proj/src:
__init__.py __init__.pyc manage.py settings.py settings.pyc
settings_local.py settings_local.pyc
urls.py urls.pyc proj
./proj/src/proj:
__init__.py admin.py auth.py facebook.py forms.py halloffame.py
helper.py image.py management
middleware.pyc models.pyc openid.pyc
stats.pyc twitter.pyc urls.pyc
views.pyc
__init__.pyc admin.pyc auth.pyc facebook.pyc forms.pyc
halloffame.pyc helper.pyc image.pyc
middleware.py models.py
openid.py stats.py twitter.py
urls.py views.py
./proj/src/proj/management:
__init__.py __init__.pyc commands
./proj/src/proj/management/commands:
__init__.py __init__.pyc cronjob.py cronjob.pyc
./proj/templates: ..../proj/templates: ...
./proj/templates: ...
Apparently (according to http://docs.python.org/whatsnew/2.5.html#pep-328), there is not way around from __future__ import absolute_import
, so I guess I'll just have to be happy with that __future__
import to resolve my name shadowing problem.
精彩评论