_field_common.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. import six
  2. import sys
  3. from pyrsistent._checked_types import (
  4. CheckedPMap,
  5. CheckedPSet,
  6. CheckedPVector,
  7. CheckedType,
  8. InvariantException,
  9. _restore_pickle,
  10. get_type,
  11. maybe_parse_user_type,
  12. maybe_parse_many_user_types,
  13. )
  14. from pyrsistent._checked_types import optional as optional_type
  15. from pyrsistent._checked_types import wrap_invariant
  16. import inspect
  17. PY2 = sys.version_info[0] < 3
  18. def set_fields(dct, bases, name):
  19. dct[name] = dict(sum([list(b.__dict__.get(name, {}).items()) for b in bases], []))
  20. for k, v in list(dct.items()):
  21. if isinstance(v, _PField):
  22. dct[name][k] = v
  23. del dct[k]
  24. def check_global_invariants(subject, invariants):
  25. error_codes = tuple(error_code for is_ok, error_code in
  26. (invariant(subject) for invariant in invariants) if not is_ok)
  27. if error_codes:
  28. raise InvariantException(error_codes, (), 'Global invariant failed')
  29. def serialize(serializer, format, value):
  30. if isinstance(value, CheckedType) and serializer is PFIELD_NO_SERIALIZER:
  31. return value.serialize(format)
  32. return serializer(format, value)
  33. def check_type(destination_cls, field, name, value):
  34. if field.type and not any(isinstance(value, get_type(t)) for t in field.type):
  35. actual_type = type(value)
  36. message = "Invalid type for field {0}.{1}, was {2}".format(destination_cls.__name__, name, actual_type.__name__)
  37. raise PTypeError(destination_cls, name, field.type, actual_type, message)
  38. def is_type_cls(type_cls, field_type):
  39. if type(field_type) is set:
  40. return True
  41. types = tuple(field_type)
  42. if len(types) == 0:
  43. return False
  44. return issubclass(get_type(types[0]), type_cls)
  45. def is_field_ignore_extra_complaint(type_cls, field, ignore_extra):
  46. # ignore_extra param has default False value, for speed purpose no need to propagate False
  47. if not ignore_extra:
  48. return False
  49. if not is_type_cls(type_cls, field.type):
  50. return False
  51. if PY2:
  52. return 'ignore_extra' in inspect.getargspec(field.factory).args
  53. else:
  54. return 'ignore_extra' in inspect.signature(field.factory).parameters
  55. class _PField(object):
  56. __slots__ = ('type', 'invariant', 'initial', 'mandatory', '_factory', 'serializer')
  57. def __init__(self, type, invariant, initial, mandatory, factory, serializer):
  58. self.type = type
  59. self.invariant = invariant
  60. self.initial = initial
  61. self.mandatory = mandatory
  62. self._factory = factory
  63. self.serializer = serializer
  64. @property
  65. def factory(self):
  66. # If no factory is specified and the type is another CheckedType use the factory method of that CheckedType
  67. if self._factory is PFIELD_NO_FACTORY and len(self.type) == 1:
  68. typ = get_type(tuple(self.type)[0])
  69. if issubclass(typ, CheckedType):
  70. return typ.create
  71. return self._factory
  72. PFIELD_NO_TYPE = ()
  73. PFIELD_NO_INVARIANT = lambda _: (True, None)
  74. PFIELD_NO_FACTORY = lambda x: x
  75. PFIELD_NO_INITIAL = object()
  76. PFIELD_NO_SERIALIZER = lambda _, value: value
  77. def field(type=PFIELD_NO_TYPE, invariant=PFIELD_NO_INVARIANT, initial=PFIELD_NO_INITIAL,
  78. mandatory=False, factory=PFIELD_NO_FACTORY, serializer=PFIELD_NO_SERIALIZER):
  79. """
  80. Field specification factory for :py:class:`PRecord`.
  81. :param type: a type or iterable with types that are allowed for this field
  82. :param invariant: a function specifying an invariant that must hold for the field
  83. :param initial: value of field if not specified when instantiating the record
  84. :param mandatory: boolean specifying if the field is mandatory or not
  85. :param factory: function called when field is set.
  86. :param serializer: function that returns a serialized version of the field
  87. """
  88. # NB: We have to check this predicate separately from the predicates in
  89. # `maybe_parse_user_type` et al. because this one is related to supporting
  90. # the argspec for `field`, while those are related to supporting the valid
  91. # ways to specify types.
  92. # Multiple types must be passed in one of the following containers. Note
  93. # that a type that is a subclass of one of these containers, like a
  94. # `collections.namedtuple`, will work as expected, since we check
  95. # `isinstance` and not `issubclass`.
  96. if isinstance(type, (list, set, tuple)):
  97. types = set(maybe_parse_many_user_types(type))
  98. else:
  99. types = set(maybe_parse_user_type(type))
  100. invariant_function = wrap_invariant(invariant) if invariant != PFIELD_NO_INVARIANT and callable(invariant) else invariant
  101. field = _PField(type=types, invariant=invariant_function, initial=initial,
  102. mandatory=mandatory, factory=factory, serializer=serializer)
  103. _check_field_parameters(field)
  104. return field
  105. def _check_field_parameters(field):
  106. for t in field.type:
  107. if not isinstance(t, type) and not isinstance(t, six.string_types):
  108. raise TypeError('Type parameter expected, not {0}'.format(type(t)))
  109. if field.initial is not PFIELD_NO_INITIAL and \
  110. not callable(field.initial) and \
  111. field.type and not any(isinstance(field.initial, t) for t in field.type):
  112. raise TypeError('Initial has invalid type {0}'.format(type(field.initial)))
  113. if not callable(field.invariant):
  114. raise TypeError('Invariant must be callable')
  115. if not callable(field.factory):
  116. raise TypeError('Factory must be callable')
  117. if not callable(field.serializer):
  118. raise TypeError('Serializer must be callable')
  119. class PTypeError(TypeError):
  120. """
  121. Raised when trying to assign a value with a type that doesn't match the declared type.
  122. Attributes:
  123. source_class -- The class of the record
  124. field -- Field name
  125. expected_types -- Types allowed for the field
  126. actual_type -- The non matching type
  127. """
  128. def __init__(self, source_class, field, expected_types, actual_type, *args, **kwargs):
  129. super(PTypeError, self).__init__(*args, **kwargs)
  130. self.source_class = source_class
  131. self.field = field
  132. self.expected_types = expected_types
  133. self.actual_type = actual_type
  134. SEQ_FIELD_TYPE_SUFFIXES = {
  135. CheckedPVector: "PVector",
  136. CheckedPSet: "PSet",
  137. }
  138. # Global dictionary to hold auto-generated field types: used for unpickling
  139. _seq_field_types = {}
  140. def _restore_seq_field_pickle(checked_class, item_type, data):
  141. """Unpickling function for auto-generated PVec/PSet field types."""
  142. type_ = _seq_field_types[checked_class, item_type]
  143. return _restore_pickle(type_, data)
  144. def _types_to_names(types):
  145. """Convert a tuple of types to a human-readable string."""
  146. return "".join(get_type(typ).__name__.capitalize() for typ in types)
  147. def _make_seq_field_type(checked_class, item_type):
  148. """Create a subclass of the given checked class with the given item type."""
  149. type_ = _seq_field_types.get((checked_class, item_type))
  150. if type_ is not None:
  151. return type_
  152. class TheType(checked_class):
  153. __type__ = item_type
  154. def __reduce__(self):
  155. return (_restore_seq_field_pickle,
  156. (checked_class, item_type, list(self)))
  157. suffix = SEQ_FIELD_TYPE_SUFFIXES[checked_class]
  158. TheType.__name__ = _types_to_names(TheType._checked_types) + suffix
  159. _seq_field_types[checked_class, item_type] = TheType
  160. return TheType
  161. def _sequence_field(checked_class, item_type, optional, initial):
  162. """
  163. Create checked field for either ``PSet`` or ``PVector``.
  164. :param checked_class: ``CheckedPSet`` or ``CheckedPVector``.
  165. :param item_type: The required type for the items in the set.
  166. :param optional: If true, ``None`` can be used as a value for
  167. this field.
  168. :param initial: Initial value to pass to factory.
  169. :return: A ``field`` containing a checked class.
  170. """
  171. TheType = _make_seq_field_type(checked_class, item_type)
  172. if optional:
  173. def factory(argument, _factory_fields=None, ignore_extra=False):
  174. if argument is None:
  175. return None
  176. else:
  177. return TheType.create(argument, _factory_fields=_factory_fields, ignore_extra=ignore_extra)
  178. else:
  179. factory = TheType.create
  180. return field(type=optional_type(TheType) if optional else TheType,
  181. factory=factory, mandatory=True,
  182. initial=factory(initial))
  183. def pset_field(item_type, optional=False, initial=()):
  184. """
  185. Create checked ``PSet`` field.
  186. :param item_type: The required type for the items in the set.
  187. :param optional: If true, ``None`` can be used as a value for
  188. this field.
  189. :param initial: Initial value to pass to factory if no value is given
  190. for the field.
  191. :return: A ``field`` containing a ``CheckedPSet`` of the given type.
  192. """
  193. return _sequence_field(CheckedPSet, item_type, optional,
  194. initial)
  195. def pvector_field(item_type, optional=False, initial=()):
  196. """
  197. Create checked ``PVector`` field.
  198. :param item_type: The required type for the items in the vector.
  199. :param optional: If true, ``None`` can be used as a value for
  200. this field.
  201. :param initial: Initial value to pass to factory if no value is given
  202. for the field.
  203. :return: A ``field`` containing a ``CheckedPVector`` of the given type.
  204. """
  205. return _sequence_field(CheckedPVector, item_type, optional,
  206. initial)
  207. _valid = lambda item: (True, "")
  208. # Global dictionary to hold auto-generated field types: used for unpickling
  209. _pmap_field_types = {}
  210. def _restore_pmap_field_pickle(key_type, value_type, data):
  211. """Unpickling function for auto-generated PMap field types."""
  212. type_ = _pmap_field_types[key_type, value_type]
  213. return _restore_pickle(type_, data)
  214. def _make_pmap_field_type(key_type, value_type):
  215. """Create a subclass of CheckedPMap with the given key and value types."""
  216. type_ = _pmap_field_types.get((key_type, value_type))
  217. if type_ is not None:
  218. return type_
  219. class TheMap(CheckedPMap):
  220. __key_type__ = key_type
  221. __value_type__ = value_type
  222. def __reduce__(self):
  223. return (_restore_pmap_field_pickle,
  224. (self.__key_type__, self.__value_type__, dict(self)))
  225. TheMap.__name__ = "{0}To{1}PMap".format(
  226. _types_to_names(TheMap._checked_key_types),
  227. _types_to_names(TheMap._checked_value_types))
  228. _pmap_field_types[key_type, value_type] = TheMap
  229. return TheMap
  230. def pmap_field(key_type, value_type, optional=False, invariant=PFIELD_NO_INVARIANT):
  231. """
  232. Create a checked ``PMap`` field.
  233. :param key: The required type for the keys of the map.
  234. :param value: The required type for the values of the map.
  235. :param optional: If true, ``None`` can be used as a value for
  236. this field.
  237. :param invariant: Pass-through to ``field``.
  238. :return: A ``field`` containing a ``CheckedPMap``.
  239. """
  240. TheMap = _make_pmap_field_type(key_type, value_type)
  241. if optional:
  242. def factory(argument):
  243. if argument is None:
  244. return None
  245. else:
  246. return TheMap.create(argument)
  247. else:
  248. factory = TheMap.create
  249. return field(mandatory=True, initial=TheMap(),
  250. type=optional_type(TheMap) if optional else TheMap,
  251. factory=factory, invariant=invariant)