Short syntax for try/pass
Leonardo Giordani
giordani.leonardo at gmail.com
Tue Oct 14 10:08:34 EDT 2014
Hi all,
a lot of times the following pattern pops out in Python code:
try:
somecode
except SomeException:
pass
A very simple example could be if you want to process a list that may be
empty
def process_list(lst):
try:
lst[0] = lst[0] + 1
except IndexError:
pass
or in more complex cases in which however an exception just signals that
there is nothing to do there.
Converting the code to a non-EAFP version, for example
if len(lst) != 0:
lst[0] = lst[0] + 1
is in my opinion generally against the Python nature, since it relies on a
specific check on the object, instead of trusting the object as being able
to either satisfy the request or raise an exception. That is, this solution
is non-polymorphic.
In such cases sometimes ABC may help, but generally speaking they it is not
always the case of being an instance of a given ABC or not. The problem
here is if the code raises an exception or not.
Would it be feasible to propose a short syntax like this?
pass SomeException:
somecode
where the above example would become:
pass IndexError:
lst[0] = lst[0] + 1
I could not find if such a syntax has been already discussed elsewhere, so
please let me know if this is the case.
Otherwise, what do you think about it?
Thank you
Leonardo
Leonardo Giordani
@tw_lgiordani <http://twitter.com/tw_lgiordani> - lgiordani.com
My profile on About.me <http://about.me/leonardo.giordani> - My GitHub page
<https://github.com/lgiordani>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20141014/98b1b2b1/attachment.html>
More information about the Python-list
mailing list