catching exceptions in expressions

Andrew Dalke adalke at mindspring.com
Wed Aug 6 21:06:04 EDT 2003


Vaclav Dvorak:
> try: c = int(u)
> except ValueError: c = 99
>
> Not enough to make me want to create a function, but enough to be
> annoying. :-) I was thinking about something like this:
>
> a = int(s) except ValueError then 99

No.  In general, Python encourages new functions or
classes over new syntax.  What's wrong with

def safe_int(s, default):
  try:
    return int(s)
  except ValueError:
    return default

or for something more generic

class TryCatcher:
  def __init__(self, function, default, exceptions = (ValueError,)):
    self.function = function
    self.default = default
    self.exceptions = exceptions
  def __call__(self, *args, **kwargs):
    try:
      return self.function(*args, **kwargs)
    except self.exceptions:
      return self.default

safe_int = TryCatcher(int, 99)
safe_int("a")


> a = int(s) or 99 if ValueError

Parse ambiguity.

  a = int(s) or 99

is valid Python today.

> a, b, c = 99, 99, 99
> try:
>          a = int(s)
>          b = int(t)
>          c = int(u)
> except ValueError:
>          continue [execution on next line - my comment]

'continue' already has meaning in current Pythons.

> Comments? Should I write a PEP? Am I missing something obvious? Has this
> been debated a million times over already?

Feel free to write a PEP.  It won't be accepted.

                    Andrew
                    dalke at dalkescientific.com






More information about the Python-list mailing list