deadpixi / contracts

An implementation of contracts for Python.
GNU Lesser General Public License v3.0
342 stars 18 forks source link

Use subtypes of AssertionError to support better handling of violations #9

Closed Zac-HD closed 6 years ago

Zac-HD commented 6 years ago

If contract violtions raised distinct subtypes of AssertionError, it would be possible to programmatically handle various kinds of contract violation. I imagine something like:

class PreconditionError(AssertionError):
    """An AssertionError raised due to violation of a precondition."""
class PostconditionError(AssertionError):
    """An AssertionError raised due to violation of a postcondition."""

# Then, to replace `if condition: assert foo, description` in each place:
if precondition and predicate(rargs):  # and similar for postconditions etc.
    raise PreconditionError(description)

This could be used by a fuzzer - e.g. HypothesisWorks/hypothesis#1474 - to automatically discover valid inputs, by distinguishing between invalid input and other errors.