00001
00002
00003
00004
00005
00006
00007
00008
00009
00010
00011
00012
00013
00014
00015 """Tools for representing JavaScript code in BSON.
00016 """
00017
00018
00019 class Code(str):
00020 """BSON's JavaScript code type.
00021
00022 Raises :class:`TypeError` if `code` is not an instance of
00023 :class:`basestring` or `scope` is not ``None`` or an instance of
00024 :class:`dict`.
00025
00026 Scope variables can be set by passing a dictionary as the `scope`
00027 argument or by using keyword arguments. If a variable is set as a
00028 keyword argument it will override any setting for that variable in
00029 the `scope` dictionary.
00030
00031 :Parameters:
00032 - `code`: string containing JavaScript code to be evaluated
00033 - `scope` (optional): dictionary representing the scope in which
00034 `code` should be evaluated - a mapping from identifiers (as
00035 strings) to values
00036 - `**kwargs` (optional): scope variables can also be passed as
00037 keyword arguments
00038
00039 .. versionadded:: 1.9
00040 Ability to pass scope values using keyword arguments.
00041 """
00042
00043 def __new__(cls, code, scope=None, **kwargs):
00044 if not isinstance(code, basestring):
00045 raise TypeError("code must be an instance of basestring")
00046
00047 self = str.__new__(cls, code)
00048
00049 try:
00050 self.__scope = code.scope
00051 except AttributeError:
00052 self.__scope = {}
00053
00054 if scope is not None:
00055 if not isinstance(scope, dict):
00056 raise TypeError("scope must be an instance of dict")
00057 self.__scope.update(scope)
00058
00059 self.__scope.update(kwargs)
00060
00061 return self
00062
00063 @property
00064 def scope(self):
00065 """Scope dictionary for this instance.
00066 """
00067 return self.__scope
00068
00069 def __repr__(self):
00070 return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
00071
00072 def __eq__(self, other):
00073 if isinstance(other, Code):
00074 return (self.__scope, str(self)) == (other.__scope, str(other))
00075 return False
00076
00077 def __ne__(self, other):
00078 return not self == other