我不认为try except块不是pythonic;相反,它是处理Python上的导入的常见方法。There are a lot of other uses for
exceptions besides handling actual
error conditions. A common use in the
standard Python library is to try to
import a module, and then check
whether it worked. Importing a module
that does not exist will raise an
ImportError exception. You can use
this to define multiple levels of
functionality based on which modules
are available at run-time, or to
support multiple platforms (where
platform-specific code is separated
into different modules).
The next example demonstrates how to
use an exception to support
platform-specific functionality.try:
import termios, TERMIOS
except ImportError:
try:
import msvcrt
except ImportError:
try:
from EasyDialogs import AskPassword
except ImportError:
getpass = default_getpass
else:
getpass = AskPassword
else:
getpass = win_getpass
else:
getpass = unix_getpass