code.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. # Copyright 2009-2015 MongoDB, Inc.
  2. #
  3. # Licensed under the Apache License, Version 2.0 (the "License");
  4. # you may not use this file except in compliance with the License.
  5. # You may obtain a copy of the License at
  6. #
  7. # http://www.apache.org/licenses/LICENSE-2.0
  8. #
  9. # Unless required by applicable law or agreed to in writing, software
  10. # distributed under the License is distributed on an "AS IS" BASIS,
  11. # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. # See the License for the specific language governing permissions and
  13. # limitations under the License.
  14. """Tools for representing JavaScript code in BSON.
  15. """
  16. import collections
  17. from bson.py3compat import string_type
  18. class Code(str):
  19. """BSON's JavaScript code type.
  20. Raises :class:`TypeError` if `code` is not an instance of
  21. :class:`basestring` (:class:`str` in python 3) or `scope`
  22. is not ``None`` or an instance of :class:`dict`.
  23. Scope variables can be set by passing a dictionary as the `scope`
  24. argument or by using keyword arguments. If a variable is set as a
  25. keyword argument it will override any setting for that variable in
  26. the `scope` dictionary.
  27. :Parameters:
  28. - `code`: string containing JavaScript code to be evaluated
  29. - `scope` (optional): dictionary representing the scope in which
  30. `code` should be evaluated - a mapping from identifiers (as
  31. strings) to values
  32. - `**kwargs` (optional): scope variables can also be passed as
  33. keyword arguments
  34. """
  35. _type_marker = 13
  36. def __new__(cls, code, scope=None, **kwargs):
  37. if not isinstance(code, string_type):
  38. raise TypeError("code must be an "
  39. "instance of %s" % (string_type.__name__))
  40. self = str.__new__(cls, code)
  41. try:
  42. self.__scope = code.scope
  43. except AttributeError:
  44. self.__scope = {}
  45. if scope is not None:
  46. if not isinstance(scope, collections.Mapping):
  47. raise TypeError("scope must be an instance of dict")
  48. self.__scope.update(scope)
  49. self.__scope.update(kwargs)
  50. return self
  51. @property
  52. def scope(self):
  53. """Scope dictionary for this instance.
  54. """
  55. return self.__scope
  56. def __repr__(self):
  57. return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
  58. def __eq__(self, other):
  59. if isinstance(other, Code):
  60. return (self.__scope, str(self)) == (other.__scope, str(other))
  61. return False
  62. def __ne__(self, other):
  63. return not self == other