Reputation: 57
I am working on some soon-to-be obsolete scientific software written in Python (Enthought Python Distribution, Python 2.7.1, IPython 0.10.1). We need to check if the older results are correct, but with the massive amount of data we have the GUI procedure we need to make working with non-GUI mode. The important piece of code is to save the data:
def _save_button_fired(self):
self.savedata()
In GUI when we click on the button the file is saved correctly. In non-GUI mode, when we do the following:
m.savedata()
the file is created, but a number of errors appear starting with:
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
etc. etc. When I use CTRL+D, select Y to kill the Python, the file is quite surprisingly written correctly. This is suffcient for our needs. However, is there any way to ignore the error and just proceed further with the code? I looked at the forum for solutions but non of them seems to fit my situation. Also, I am not keen on Python, thus would be grateful for a working solution. With many thanks.
Upvotes: 1
Views: 6705
Reputation: 1726
An alternative to the try/pass
solution is contextlib.suppress
.
with contextlib.suppress(TypeError):
self.savedata()
Why one over the other?
The context manager slightly shortens the code and significantly clarifies the author's intention to ignore the specific errors. The standard library feature was introduced following a discussion, where the consensus was that: A key benefit here is in the priming effect for readers... The with statement form makes it clear before you start reading the code that certain exceptions won't propagate.
Source: sourcery.ai
Upvotes: 0
Reputation: 1602
You could wrap it in a try/pass :)
try:
self.savedata()
except TypeError:
pass
Upvotes: 4