Skip to content

Support for any iterable (instead of just list) in "allowed" rule. #384

@crunk1

Description

@crunk1

Used Cerberus version / latest commit: 1.2
Python version: 3.6.5


Use-case abstract

I suggest adding support for using iterables in the "allowed" validation rule. In particular, I have a string enum class derived from enum.Enum. An enum.Enum is iterable. I'll try to demonstrate my use case:

class MyEnum(StrEnum):
  FOO = 'FOO'

# Behavior of MyEnum
# list(MyEnum)         -> [<MyEnum.FOO: 'FOO'>]
# 'FOO' in MyEnum      -> True
# 'BAR' in MyEnum      -> False
# MyEnum.FOO in MyEnum -> True
# MyEnum.FOO == 'FOO'  -> True
# MyEnum.FOO == 'BAR'  -> False

# This works, but is undesirable:
schema = {
  'foo': {'type': 'list', 'allowed': list(MyEnum)},
}
v = cerberus.Validator(schema)
# v.validate({'foo': [MyEnum.FOO, 'FOO']}) -> True

# This raises an error:
schema = {
  'foo': {'type': 'list', 'allowed': MyEnum},
}
v = cerberus.Validator(schema)
# Traceback (most recent call last):
#   File "<input>", line 1, in <module>
#   File "C:\Python36\lib\site-packages\cerberus\validator.py", line 169, in __init__
#     self.schema = kwargs.get('schema', None)
#   File "C:\Python36\lib\site-packages\cerberus\validator.py", line 509, in schema
#     self._schema = DefinitionSchema(self, schema)
#   File "C:\Python36\lib\site-packages\cerberus\schema.py", line 69, in __init__
#     self.validate(schema)
#   File "C:\Python36\lib\site-packages\cerberus\schema.py", line 197, in validate
#     self._validate(schema)
#   File "C:\Python36\lib\site-packages\cerberus\schema.py", line 219, in _validate
#     raise SchemaError(self.schema_validator.errors)
# cerberus.schema.SchemaError: {'foo': [{'allowed': ['must be of list type']}]}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions