Idiom for partial failures

Tim Chase python.list at tim.thechases.com
Thu Feb 20 17:25:43 EST 2020


On 2020-02-20 13:30, David Wihl wrote:
> I believe that it would be more idiomatic in Python (and other
> languages like Ruby) to throw an exception when one of these
> partial errors occur. That way there would be the same control flow
> if a major or minor error occurred. 

There are a variety of ways to do it -- I like Ethan's suggestion
about tacking the failures onto the exception and raising it at the
end.  But you can also yield a tuple of success/failure iterators,
something like this pseudocode:

  def process(input_iter):
    successes = []
    failures = []
    for thing in input_iter:
      try:
        result = process(thing)
      except ValueError as e: # catch appropriate exception(s) here
        failures.append((e, thing))
      else:
        successes.append((result, thing))
    return successes, failures

  def process(item):
    if item % 3:
      raise ValueError("Must be divisible by 3!")
    else:
      print(item)
      return item // 3

  successes, failures = process(range(10))

  for reason, thing in failures:
    print(f"Unable to process {thing} because {reason}")

-tkc





More information about the Python-list mailing list