ImportError: cannot import name NO_DEFAULT
I'm trying to run a Django site's manage.py
script, but it fails with the following error:
Traceback (most recent call last):
File "manage.py", line 2, in <module>
from django.core.management import execute_manager
File "/scratch/tools/lib/python2.5/site-packages/django/core/management/__init__.py", line 4, in <module>
from optparse import OptionParser, NO_DEFAULT
ImportError: cannot import name NO_DEFAULT
This happens regardless of whether I use Python开发者_运维知识库 2.5.1 or 2.6.1 (Fedora packages). I can reproduce the error when doing the import in an interactive Python session.
This is not very surprising, considering that NO_DEFAULT
is not listed in optparse.py
's __all__
and is also not listed in the optparse
documentation.
What is surprising, then, is that on my own workstation I can successfully do from optparse import NO_DEFAULT
in both Python 2.5.5 and 2.6.6 (Debian packages).
My question is twofold:
- How can it be that I can import something that is not listed in
__all__
? - How should I fix the Django
manage.py
? I want it to work with Python 2.5, if at all possible.
As always in Python, __all__
is more of a guideline than a rule. It comes about because of the we-love-to-hate-it *-import
, described in the docs as
If the list of identifiers is replaced by a star ('*'), all public names defined in the module are bound in the local namespace of the
import
statement.
There is an immediate technical difficulty here: how should the interpreter know what the public names of a module are? There is a convention that any name in a module not beginning with an _
is public; you might think that as a first approximation one should simply import all such names in the module's namespace. Unfortunately, this becomes more complicated when you introduce packages, because then computing the public names becomes a large task involving various imports, path rewrites, file reads, and what have you. This is not a good thing. Thus, the simplifying decision was taken to allow the module author to specify exactly which names in the package should be imported from a *-import, by defining __all__
in the module.
But if you don't *-import -- if you give the interpreter the name of the variable you want to import -- then it doesn't need to worry about finding all the global names, so it can ignore __all__
and just look up the name in the module's namespace.
That does mean that __all__
may not be the same as the subset of locals().keys()
not starting with an underscore. In particular, there may be perfectly good objects in the module which are not exported by *-imports. This is what happens with NO_DEFAULT
.
精彩评论