utils.py 3.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119
  1. from __future__ import absolute_import
  2. from collections import Mapping, namedtuple, Sequence
  3. from cerberus.platform import _int_types, _str_type
  4. TypeDefinition = namedtuple('TypeDefinition',
  5. 'name,included_types,excluded_types')
  6. """
  7. This class is used to define types that can be used as value in the
  8. :attr:`~cerberus.Validator.types_mapping` property.
  9. The ``name`` should be descriptive and match the key it is going to be assigned
  10. to.
  11. A value that is validated against such definition must be an instance of any of
  12. the types contained in ``included_types`` and must not match any of the types
  13. contained in ``excluded_types``.
  14. """
  15. def compare_paths_lt(x, y):
  16. for i in range(min(len(x), len(y))):
  17. if isinstance(x[i], type(y[i])):
  18. if x[i] != y[i]:
  19. return x[i] < y[i]
  20. elif isinstance(x[i], _int_types):
  21. return True
  22. elif isinstance(y[i], _int_types):
  23. return False
  24. return len(x) < len(y)
  25. def drop_item_from_tuple(t, i):
  26. return t[:i] + t[i + 1:]
  27. def get_Validator_class():
  28. global Validator
  29. if 'Validator' not in globals():
  30. from cerberus.validator import Validator
  31. return Validator
  32. def mapping_hash(schema):
  33. return hash(mapping_to_frozenset(schema))
  34. def mapping_to_frozenset(mapping):
  35. """ Be aware that this treats any sequence type with the equal members as
  36. equal. As it is used to identify equality of schemas, this can be
  37. considered okay as definitions are semantically equal regardless the
  38. container type. """
  39. mapping = mapping.copy()
  40. for key, value in mapping.items():
  41. if isinstance(value, Mapping):
  42. mapping[key] = mapping_to_frozenset(value)
  43. elif isinstance(value, Sequence):
  44. value = list(value)
  45. for i, item in enumerate(value):
  46. if isinstance(item, Mapping):
  47. value[i] = mapping_to_frozenset(item)
  48. mapping[key] = tuple(value)
  49. return frozenset(mapping.items())
  50. def isclass(obj):
  51. try:
  52. issubclass(obj, object)
  53. except TypeError:
  54. return False
  55. else:
  56. return True
  57. def quote_string(value):
  58. if isinstance(value, _str_type):
  59. return '"%s"' % value
  60. else:
  61. return value
  62. class readonly_classproperty(property):
  63. def __get__(self, instance, owner):
  64. return super(readonly_classproperty, self).__get__(owner)
  65. def __set__(self, instance, value):
  66. raise RuntimeError('This is a readonly class property.')
  67. def __delete__(self, instance):
  68. raise RuntimeError('This is a readonly class property.')
  69. def validator_factory(name, bases=None, namespace={}):
  70. """ Dynamically create a :class:`~cerberus.Validator` subclass.
  71. Docstrings of mixin-classes will be added to the resulting
  72. class' one if ``__doc__`` is not in :obj:`namespace`.
  73. :param name: The name of the new class.
  74. :type name: :class:`str`
  75. :param bases: Class(es) with additional and overriding attributes.
  76. :type bases: :class:`tuple` of or a single :term:`class`
  77. :param namespace: Attributes for the new class.
  78. :type namespace: :class:`dict`
  79. :return: The created class.
  80. """
  81. Validator = get_Validator_class()
  82. if bases is None:
  83. bases = (Validator,)
  84. elif isinstance(bases, tuple):
  85. bases += (Validator,)
  86. else:
  87. bases = (bases, Validator)
  88. docstrings = [x.__doc__ for x in bases if x.__doc__]
  89. if len(docstrings) > 1 and '__doc__' not in namespace:
  90. namespace.update({'__doc__': '\n'.join(docstrings)})
  91. return type(name, bases, namespace)