Skip to content

Raise LengthInvalid (not RangeInvalid) for non-sized values in Length - #551

Open
uttam12331 wants to merge 1 commit into
alecthomas:masterfrom
uttam12331:fix/length-typeerror-raises-lengthinvalid
Open

Raise LengthInvalid (not RangeInvalid) for non-sized values in Length#551
uttam12331 wants to merge 1 commit into
alecthomas:masterfrom
uttam12331:fix/length-typeerror-raises-lengthinvalid

Conversation

@uttam12331

Copy link
Copy Markdown
Contributor

Summary

Length.__call__ raises LengthInvalid for its length checks, but the except TypeError handler raises RangeInvalid:

def __call__(self, v):
    try:
        if self.min is not None and len(v) < self.min:
            raise LengthInvalid(self.msg or 'length of value must be at least %s' % self.min)
        if self.max is not None and len(v) > self.max:
            raise LengthInvalid(self.msg or 'length of value must be at most %s' % self.max)
        return v
    # Objects that have no length e.g. None or strings will raise TypeError
    except TypeError:
        raise RangeInvalid(self.msg or 'invalid value or type')   # <-- should be LengthInvalid

When a value with no len() (e.g. None, or an int) is passed to a Length validator, the error is reported as a range error rather than a length error — inconsistent with the validator's own two other error paths.

This looks like a copy-paste leftover from the Clamp validator directly above, which is genuinely a range operation and correctly raises RangeInvalid in its own except TypeError.

Fix

     except TypeError:
-        raise RangeInvalid(self.msg or 'invalid value or type')
+        raise LengthInvalid(self.msg or 'invalid value or type')

LengthInvalid is already imported at the top of the module.

Tests

Tightened test_length_invalid to assert the raised error is a LengthInvalid. It fails on the previous behavior (RangeInvalid) and passes with the fix. Full suite: 181 passed.

Length.__call__ raises LengthInvalid for its min/max length checks, but its
`except TypeError` handler (hit when the value has no len(), e.g. None or an
int) raises RangeInvalid instead -- a copy-paste leftover from the Clamp
validator above, which is genuinely a range operation. Passing a non-sized
value to a Length validator therefore reports a range error rather than a
length error, inconsistent with the validator's own two other error paths.

Raise LengthInvalid, and tighten test_length_invalid to assert the error type.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant