m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.3 KiB

6 months ago
  1. #
  2. # Licensed under the Apache License, Version 2.0 (the "License"); you may
  3. # not use this file except in compliance with the License. You may obtain
  4. # a copy of the License at
  5. #
  6. # http://www.apache.org/licenses/LICENSE-2.0
  7. #
  8. # Unless required by applicable law or agreed to in writing, software
  9. # distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  10. # WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  11. # License for the specific language governing permissions and limitations
  12. # under the License.
  13. import operator
  14. from .. import JSONPath, DatumInContext
  15. OPERATOR_MAP = {
  16. '+': operator.add,
  17. '-': operator.sub,
  18. '*': operator.mul,
  19. '/': operator.truediv,
  20. }
  21. class Operation(JSONPath):
  22. def __init__(self, left, op, right):
  23. self.left = left
  24. self.op = OPERATOR_MAP[op]
  25. self.right = right
  26. def find(self, datum):
  27. result = []
  28. if (isinstance(self.left, JSONPath)
  29. and isinstance(self.right, JSONPath)):
  30. left = self.left.find(datum)
  31. right = self.right.find(datum)
  32. if left and right and len(left) == len(right):
  33. for l, r in zip(left, right):
  34. try:
  35. result.append(self.op(l.value, r.value))
  36. except TypeError:
  37. return []
  38. else:
  39. return []
  40. elif isinstance(self.left, JSONPath):
  41. left = self.left.find(datum)
  42. for l in left:
  43. try:
  44. result.append(self.op(l.value, self.right))
  45. except TypeError:
  46. return []
  47. elif isinstance(self.right, JSONPath):
  48. right = self.right.find(datum)
  49. for r in right:
  50. try:
  51. result.append(self.op(self.left, r.value))
  52. except TypeError:
  53. return []
  54. else:
  55. try:
  56. result.append(self.op(self.left, self.right))
  57. except TypeError:
  58. return []
  59. return [DatumInContext.wrap(r) for r in result]
  60. def __repr__(self):
  61. return '%s(%r%s%r)' % (self.__class__.__name__, self.left, self.op,
  62. self.right)
  63. def __str__(self):
  64. return '%s%s%s' % (self.left, self.op, self.right)