English 中文(简体)
Python try...except comma vs as in except
原标题:

What is the difference between , and as in except statements, eg:

try:
    pass
except Exception, exception:
    pass

and:

try:
    pass
except Exception as exception:
    pass

Is the second syntax legal in 2.6? It works in CPython 2.6 on Windows but the 2.5 interpreter in cygwin complains that it is invalid.

If they are both valid in 2.6 which should I use?

最佳回答

The definitive document is PEP-3110: Catching Exceptions

Summary:

  • In Python 3.x, using as is required to assign an exception to a variable.
  • In Python 2.6+, use the as syntax, since it is far less ambiguous and forward compatible with Python 3.x.
  • In Python 2.5 and earlier, use the comma version, since as isn t supported.
问题回答

Yes it s legal. I m running Python 2.6

try:
    [] + 3
except Exception as x:
    print "woo hoo"

>>> 
woo hoo

Update: There is another reason to use the as syntax. Using , makes things a lot more ambiguous, as others have pointed out; and here s what makes the difference. As of Python 2.6, there is multicatch which allows you to catch multiple exceptions in one except block. In such a situation, it s more expressive and pythonic to say

except (exception1, exception2) as e

rather than to say

except (exception1, exception2), e

which would still work

the "as" syntax is the preferred one going forward, however if your code needs to work with older Python versions (2.6 is the first to support the new one) then you ll need to use the comma syntax.

If you want to support all python versions you can use the sys.exc_info() function like this:

try:
    a = 1/ 0 
except (ZeroDivisionError, TypeError):
    e = sys.exc_info()[1]
    print(e.args[0])

(source:http://python3porting.com/noconv.html)

As of Python 3.7 (not sure about other versions) the comma syntax is not supported any more:

Source file exception_comma.py:

try:
    result = 1/0
except Exception, e:
    print("An error occurred")
    exit(1)

exit(0)
  • $ python --version --> Python 2.7.10
$ python exception_comma.py
An error occurred
  • $ python3 --version --> Python 3.7.2
$ python3 exception_comma.py
  File "exception_comma.py", line 3
    except Exception, e:
                    ^
SyntaxError: invalid syntax




相关问题
Can Django models use MySQL functions?

Is there a way to force Django models to pass a field to a MySQL function every time the model data is read or loaded? To clarify what I mean in SQL, I want the Django model to produce something like ...

An enterprise scheduler for python (like quartz)

I am looking for an enterprise tasks scheduler for python, like quartz is for Java. Requirements: Persistent: if the process restarts or the machine restarts, then all the jobs must stay there and ...

How to remove unique, then duplicate dictionaries in a list?

Given the following list that contains some duplicate and some unique dictionaries, what is the best method to remove unique dictionaries first, then reduce the duplicate dictionaries to single ...

What is suggested seed value to use with random.seed()?

Simple enough question: I m using python random module to generate random integers. I want to know what is the suggested value to use with the random.seed() function? Currently I am letting this ...

How can I make the PyDev editor selectively ignore errors?

I m using PyDev under Eclipse to write some Jython code. I ve got numerous instances where I need to do something like this: import com.work.project.component.client.Interface.ISubInterface as ...

How do I profile `paster serve` s startup time?

Python s paster serve app.ini is taking longer than I would like to be ready for the first request. I know how to profile requests with middleware, but how do I profile the initialization time? I ...

Pragmatically adding give-aways/freebies to an online store

Our business currently has an online store and recently we ve been offering free specials to our customers. Right now, we simply display the special and give the buyer a notice stating we will add the ...

Converting Dictionary to List? [duplicate]

I m trying to convert a Python dictionary into a Python list, in order to perform some calculations. #My dictionary dict = {} dict[ Capital ]="London" dict[ Food ]="Fish&Chips" dict[ 2012 ]="...

热门标签