Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #79096

Short syntax for try/pass

Date 2014-10-14 16:08 +0200
Subject Short syntax for try/pass
From Leonardo Giordani <giordani.leonardo@gmail.com>
Newsgroups comp.lang.python
Message-ID <mailman.14848.1413295744.18130.python-list@python.org> (permalink)

Show all headers | View raw


[Multipart message — attachments visible in raw view] - view raw

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>

Back to comp.lang.python | Previous | Next | Find similar | Unroll thread


Thread

Short syntax for try/pass Leonardo Giordani <giordani.leonardo@gmail.com> - 2014-10-14 16:08 +0200

csiph-web