BSON's JavaScript code type. Raises :class:`TypeError` if `code` is not an instance of :class:`str` or `scope` is not ``None`` or an instance of :class:`dict`. Scope variables can be set by passing a dictionary as the `scope` argument or by using keyword arguments. If a variabl
| 20 | |
| 21 | |
| 22 | class Code(str): |
| 23 | """BSON's JavaScript code type. |
| 24 | |
| 25 | Raises :class:`TypeError` if `code` is not an instance of |
| 26 | :class:`str` or `scope` is not ``None`` or an instance |
| 27 | 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 | :param 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 | :param scope: 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 | :param kwargs: 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 | __scope: Union[Mapping[str, Any], None] |
| 51 | |
| 52 | def __new__( |
| 53 | cls: Type[Code], |
| 54 | code: Union[str, Code], |
| 55 | scope: Optional[Mapping[str, Any]] = None, |
| 56 | **kwargs: Any, |
| 57 | ) -> Code: |
| 58 | if not isinstance(code, str): |
| 59 | raise TypeError(f"code must be an instance of str, not {type(code)}") |
| 60 | |
| 61 | self = str.__new__(cls, code) |
| 62 | |
| 63 | try: |
| 64 | self.__scope = code.scope # type: ignore |
| 65 | except AttributeError: |
| 66 | self.__scope = None |
| 67 | |
| 68 | if scope is not None: |
| 69 | if not isinstance(scope, _Mapping): |
| 70 | raise TypeError(f"scope must be an instance of dict, not {type(scope)}") |
| 71 | if self.__scope is not None: |
| 72 | self.__scope.update(scope) # type: ignore |
| 73 | else: |
| 74 | self.__scope = scope |
| 75 | |
| 76 | if kwargs: |
| 77 | if self.__scope is not None: |
| 78 | self.__scope.update(kwargs) # type: ignore |
| 79 | else: |
no outgoing calls