Skip to content

Commit

Permalink
Modified __lt__ in Marker class.
Browse files Browse the repository at this point in the history
Marker class in /voluptuous/schema_builder.py needed to have the __lt__() function
modified in order to compare against regular strings as well.

This will allow the usage of Voluptuous Optional objects as keys in dicts alongside
strings and int.
  • Loading branch information
Mohammed Mohammed committed Feb 14, 2018
1 parent a206303 commit c35c76a
Show file tree
Hide file tree
Showing 4 changed files with 29 additions and 1 deletion.
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,8 @@
Treat Python 2 old-style classes like types when validating.
- [324](https://github.com/alecthomas/voluptuous/pull/324):
Default values MUST now pass validation just as any regular value. This is a backward incompatible change if a schema uses default values that don't pass validation against the specified schema.
- [328](https://github.com/alecthomas/voluptuous/pull/328):
Modified __lt__ in Marker class to allow comparison with non Marker objects, such as str and int

## [0.10.5]

Expand Down
4 changes: 3 additions & 1 deletion voluptuous/schema_builder.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,7 +953,9 @@ def __repr__(self):
return repr(self.schema)

def __lt__(self, other):
return self.schema < other.schema
if isinstance(other, Marker):
return self.schema < other.schema
return self.schema < other

def __hash__(self):
return hash(self.schema)
Expand Down
5 changes: 5 additions & 0 deletions voluptuous/tests/tests.md
Original file line number Diff line number Diff line change
Expand Up @@ -266,3 +266,8 @@ Ensure that subclasses of Invalid of are raised as is.
... exc = e
>>> exc.errors[0].__class__.__name__
'SpecialInvalid'

Ensure that Optional('Classification') < 'Name' will return True instead of throwing an AttributeError

>>> Optional('Classification') < 'Name'
True
19 changes: 19 additions & 0 deletions voluptuous/tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -1137,3 +1137,22 @@ def test_self_all():
def test_SomeOf_on_bounds_assertion():
with raises(AssertionError, 'when using "SomeOf" you should specify at least one of min_valid and max_valid'):
SomeOf(validators=[])


def test_sorting_dict_with_voluptuous_objects_and_str():
schema_with_voluptuous_object = {
'Name': 'Mo',
'ExecutionTimestamp': 'Today',
Optional('Classification'): [Any(['A+', 'B+'])]
}
schema_without_voluptuous_object = {
'Name': 'Mo',
'ExecutionTimestamp': 'Today',
'Classification': [Any(['A+', 'B+'])]
}

assert_true(sorted(schema_with_voluptuous_object), sorted(schema_without_voluptuous_object))


def test_comparing_voluptuous_object_to_str():
assert_true(Optional('Classification') < 'Name')

0 comments on commit c35c76a

Please sign in to comment.