Skip to content

Commit f51d83d

Browse files
author
Mike Dirolf
committed
allow specifying scope variables as keyword arguments
1 parent 8098845 commit f51d83d

File tree

2 files changed

+31
-11
lines changed

2 files changed

+31
-11
lines changed

pymongo/code.py

Lines changed: 25 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -20,30 +20,44 @@ class Code(str):
2020
"""JavaScript code to be evaluated by MongoDB.
2121
2222
Raises :class:`TypeError` if `code` is not an instance of
23-
:class:`basestring` or `scope` is not an instance of
23+
:class:`basestring` or `scope` is not ``None`` or an instance of
2424
:class:`dict`.
2525
26+
Scope variables can be set by passing a dictionary as the `scope`
27+
argument or by using keyword arguments. If a variable is set as a
28+
keyword argument it will override any setting for that variable in
29+
the `scope` dictionary.
30+
2631
:Parameters:
2732
- `code`: string containing JavaScript code to be evaluated
2833
- `scope` (optional): dictionary representing the scope in which
2934
`code` should be evaluated - a mapping from identifiers (as
3035
strings) to values
36+
- `**kwargs` (optional): scope variables can also be passed as
37+
keyword arguments
38+
39+
.. versionadded:: 1.8.1+
40+
Ability to pass scope values using keyword arguments.
3141
"""
3242

33-
def __new__(cls, code, scope=None):
43+
def __new__(cls, code, scope=None, **kwargs):
3444
if not isinstance(code, basestring):
3545
raise TypeError("code must be an instance of basestring")
3646

37-
if scope is None:
38-
try:
39-
scope = code.scope
40-
except AttributeError:
41-
scope = {}
42-
if not isinstance(scope, dict):
43-
raise TypeError("scope must be an instance of dict")
44-
4547
self = str.__new__(cls, code)
46-
self.__scope = scope
48+
49+
try:
50+
self.__scope = code.scope
51+
except AttributeError:
52+
self.__scope = {}
53+
54+
if scope is not None:
55+
if not isinstance(scope, dict):
56+
raise TypeError("scope must be an instance of dict")
57+
self.__scope.update(scope)
58+
59+
self.__scope.update(kwargs)
60+
4761
return self
4862

4963
@property

test/test_code.py

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -84,6 +84,12 @@ def test_scope_preserved(self):
8484
self.assertNotEqual(a, Code(b))
8585
self.assertNotEqual(b, Code(a))
8686

87+
def test_scope_kwargs(self):
88+
self.assertEqual({"a": 1}, Code("", a=1).scope)
89+
self.assertEqual({"a": 1}, Code("", {"a": 2}, a=1).scope)
90+
self.assertEqual({"a": 1, "b": 2, "c": 3},
91+
Code("", {"b": 2}, a=1, c=3).scope)
92+
8793

8894
if __name__ == "__main__":
8995
unittest.main()

0 commit comments

Comments
 (0)