except 语句中 ',' 和 'as' 有什么区别,例如:
try:
pass
except Exception, exception:
pass
和:
try:
pass
except Exception as exception:
pass
第二种语法在 2.6 中合法吗?它适用于 Windows 上的 CPython 2.6,但 cygwin 中的 2.5 解释器提示它无效。
如果它们在 2.6 中都有效,我应该使用哪个?
最佳答案
权威文件是PEP-3110: Catching Exceptions
总结:
- 在 Python 3.x 中,需要使用
as
将异常分配给变量。 - 在 Python 2.6+ 中,使用
as
语法,因为它的歧义少得多并且与 Python 3.x 向前兼容。 - 在 Python 2.5 及更早版本中,使用逗号版本,因为不支持
as
。
关于Python try...except 逗号 vs 'as' in except,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9084755/