[Python-ideas] except expression

David Mertz mertz at gnosis.cx
Thu Feb 20 19:32:44 CET 2014


On Thu, Feb 20, 2014 at 5:45 AM, M.-A. Lemburg <mal at egenix.com> wrote:

> x = data[1] except IndexError return None # is readable
> f = open('x.txt', 'r') except IOError return None # is probably not a good
> idea
> os.remove('/') except IOError return None # is really bad style
>

I agree with the comments, but I think the middle one doesn't present the
usage that really *would* be useful:

  # Fallback to other file-like object
  f = open('x.txt') except IOError return io.StringIO('')
  g = open('y.txt') except IOError return urlopen('http://the.remote/y.txt')

  # Sometimes we want the content of files
  txt = open('x.txt').read() except IOError return ''

I completely agree that something one calls entirely for its side effect,
not its value, is a terrible use for except expressions.

-- 
Keeping medicines from the bloodstreams of the sick; food
from the bellies of the hungry; books from the hands of the
uneducated; technology from the underdeveloped; and putting
advocates of freedom in prisons.  Intellectual property is
to the 21st century what the slave trade was to the 16th.
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20140220/1cd8bcc8/attachment.html>


More information about the Python-ideas mailing list