Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]
Groups > comp.lang.python > #79098
| References | <CAEhE+OknxQs0XdENq_MR=HyER1qz5_JXXRHxO35RYV3h-K13KQ@mail.gmail.com> |
|---|---|
| Date | 2014-10-15 01:22 +1100 |
| Subject | Re: Short syntax for try/pass |
| From | Chris Angelico <rosuav@gmail.com> |
| Newsgroups | comp.lang.python |
| Message-ID | <mailman.14850.1413296526.18130.python-list@python.org> (permalink) |
On Wed, Oct 15, 2014 at 1:08 AM, Leonardo Giordani
<giordani.leonardo@gmail.com> wrote:
> a lot of times the following pattern pops out in Python code:
>
> try:
> somecode
> except SomeException:
> pass
>
> Converting the code to a non-EAFP version, for example
>
> if len(lst) != 0:
> lst[0] = lst[0] + 1
This could be just "if lst:", but I agree, LBYL is not Python's style
(and isn't always possible anyway).
You can at least squish it up onto less lines, which might look better:
try: lst[0] += 1
except IndexError: pass
Alternatively, you can use this style:
from contextlib import suppress
with suppress(IndexError):
lst[0] += 1
ChrisA
Back to comp.lang.python | Previous | Next | Find similar | Unroll thread
Re: Short syntax for try/pass Chris Angelico <rosuav@gmail.com> - 2014-10-15 01:22 +1100
csiph-web