xtquant.xtbson.bson36.code

Tools for representing JavaScript code in BSON.

 1# Copyright 2009-present 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
15"""Tools for representing JavaScript code in BSON.
16"""
17
18from collections.abc import Mapping as _Mapping
19
20
21class Code(str):
22    """BSON's JavaScript code type.
23
24    Raises :class:`TypeError` if `code` is not an instance of
25    :class:`basestring` (:class:`str` in python 3) or `scope`
26    is not ``None`` or an instance of :class:`dict`.
27
28    Scope variables can be set by passing a dictionary as the `scope`
29    argument or by using keyword arguments. If a variable is set as a
30    keyword argument it will override any setting for that variable in
31    the `scope` dictionary.
32
33    :Parameters:
34      - `code`: A string containing JavaScript code to be evaluated or another
35        instance of Code. In the latter case, the scope of `code` becomes this
36        Code's :attr:`scope`.
37      - `scope` (optional): dictionary representing the scope in which
38        `code` should be evaluated - a mapping from identifiers (as
39        strings) to values. Defaults to ``None``. This is applied after any
40        scope associated with a given `code` above.
41      - `**kwargs` (optional): scope variables can also be passed as
42        keyword arguments. These are applied after `scope` and `code`.
43
44    .. versionchanged:: 3.4
45      The default value for :attr:`scope` is ``None`` instead of ``{}``.
46
47    """
48
49    _type_marker = 13
50
51    def __new__(cls, code, scope=None, **kwargs):
52        if not isinstance(code, str):
53            raise TypeError("code must be an instance of str")
54
55        self = str.__new__(cls, code)
56
57        try:
58            self.__scope = code.scope
59        except AttributeError:
60            self.__scope = None
61
62        if scope is not None:
63            if not isinstance(scope, _Mapping):
64                raise TypeError("scope must be an instance of dict")
65            if self.__scope is not None:
66                self.__scope.update(scope)
67            else:
68                self.__scope = scope
69
70        if kwargs:
71            if self.__scope is not None:
72                self.__scope.update(kwargs)
73            else:
74                self.__scope = kwargs
75
76        return self
77
78    @property
79    def scope(self):
80        """Scope dictionary for this instance or ``None``."""
81        return self.__scope
82
83    def __repr__(self):
84        return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
85
86    def __eq__(self, other):
87        if isinstance(other, Code):
88            return (self.__scope, str(self)) == (other.__scope, str(other))
89        return False
90
91    __hash__ = None
92
93    def __ne__(self, other):
94        return not self == other
class Code(builtins.str):
22class Code(str):
23    """BSON's JavaScript code type.
24
25    Raises :class:`TypeError` if `code` is not an instance of
26    :class:`basestring` (:class:`str` in python 3) or `scope`
27    is not ``None`` or an instance of :class:`dict`.
28
29    Scope variables can be set by passing a dictionary as the `scope`
30    argument or by using keyword arguments. If a variable is set as a
31    keyword argument it will override any setting for that variable in
32    the `scope` dictionary.
33
34    :Parameters:
35      - `code`: A string containing JavaScript code to be evaluated or another
36        instance of Code. In the latter case, the scope of `code` becomes this
37        Code's :attr:`scope`.
38      - `scope` (optional): dictionary representing the scope in which
39        `code` should be evaluated - a mapping from identifiers (as
40        strings) to values. Defaults to ``None``. This is applied after any
41        scope associated with a given `code` above.
42      - `**kwargs` (optional): scope variables can also be passed as
43        keyword arguments. These are applied after `scope` and `code`.
44
45    .. versionchanged:: 3.4
46      The default value for :attr:`scope` is ``None`` instead of ``{}``.
47
48    """
49
50    _type_marker = 13
51
52    def __new__(cls, code, scope=None, **kwargs):
53        if not isinstance(code, str):
54            raise TypeError("code must be an instance of str")
55
56        self = str.__new__(cls, code)
57
58        try:
59            self.__scope = code.scope
60        except AttributeError:
61            self.__scope = None
62
63        if scope is not None:
64            if not isinstance(scope, _Mapping):
65                raise TypeError("scope must be an instance of dict")
66            if self.__scope is not None:
67                self.__scope.update(scope)
68            else:
69                self.__scope = scope
70
71        if kwargs:
72            if self.__scope is not None:
73                self.__scope.update(kwargs)
74            else:
75                self.__scope = kwargs
76
77        return self
78
79    @property
80    def scope(self):
81        """Scope dictionary for this instance or ``None``."""
82        return self.__scope
83
84    def __repr__(self):
85        return "Code(%s, %r)" % (str.__repr__(self), self.__scope)
86
87    def __eq__(self, other):
88        if isinstance(other, Code):
89            return (self.__scope, str(self)) == (other.__scope, str(other))
90        return False
91
92    __hash__ = None
93
94    def __ne__(self, other):
95        return not self == other

BSON's JavaScript code type.

Raises TypeError if code is not an instance of basestring (str in python 3) or scope is not None or an instance of dict.

Scope variables can be set by passing a dictionary as the scope argument or by using keyword arguments. If a variable is set as a keyword argument it will override any setting for that variable in the scope dictionary.

:Parameters:

  • code: A string containing JavaScript code to be evaluated or another instance of Code. In the latter case, the scope of code becomes this Code's scope.
  • scope (optional): dictionary representing the scope in which code should be evaluated - a mapping from identifiers (as strings) to values. Defaults to None. This is applied after any scope associated with a given code above.
  • **kwargs (optional): scope variables can also be passed as keyword arguments. These are applied after scope and code.

Changed in version 3.4: The default value for scope is None instead of {}.

scope

Scope dictionary for this instance or None.

Inherited Members
builtins.str
encode
replace
split
rsplit
join
capitalize
casefold
title
center
count
expandtabs
find
partition
index
ljust
lower
lstrip
rfind
rindex
rjust
rstrip
rpartition
splitlines
strip
swapcase
translate
upper
startswith
endswith
removeprefix
removesuffix
isascii
islower
isupper
istitle
isspace
isdecimal
isdigit
isnumeric
isalpha
isalnum
isidentifier
isprintable
zfill
format
format_map
maketrans