[Python-Dev] suggestion: except in list comprehension

Josiah Carlson jcarlson at uci.edu
Wed Apr 26 19:51:33 CEST 2006


"tomer filiba" <tomerfiliba at gmail.com> wrote:
> "[" <expr> for <expr> in <expr> [if <cond>] [except
> <exception-class-or-tuple>: <action>] "]"

Note that of the continue cases you offer, all of them are merely simple
if condition (though the file example could use a better test than
os.path.isfile).
 [x for x in a if x.startswith("y") except AttributeError: continue]
 [x for x in a if hasattr(x, 'startswith') and x.startswith("y")]
 [1.0 / x for x in y except ZeroDivisionError: continue]
 [1.0 / x for x in y if x != 0]
 [open(filename) for filename in filelist except IOError: continue]
 [open(filename) for filename in filelist if os.path.isfile(filename)]
The break case can be implemented with particular kind of instance
object, though doesn't have the short-circuiting behavior...
class StopWhenFalse:
 def __init__(self):
 self.t = 1
 def __call__(self, t):
 if not t:
 self.t = 0
 return 0
 return self.t
z = StopWhenFalse()
Assuming you create a new instance z of StopWhenFalse before doing the
list comprehensions...
 [x for x in a if z(hasattr(x, 'startswith') and x.startswith("y"))]
 [1.0 / x for x in y if z(x != 0)]
 [open(filename) for filename in filelist if z(os.path.isfile(filename))]
If you couldn't guess; -1, you can get equivalent behavior without
complicating the generator expression/list comprension syntax.
 - Josiah


More information about the Python-Dev mailing list

AltStyle によって変換されたページ (->オリジナル) /