@@ -20,30 +20,44 @@ class Code(str):
20
20
"""JavaScript code to be evaluated by MongoDB.
21
21
22
22
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
24
24
:class:`dict`.
25
25
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
+
26
31
:Parameters:
27
32
- `code`: string containing JavaScript code to be evaluated
28
33
- `scope` (optional): dictionary representing the scope in which
29
34
`code` should be evaluated - a mapping from identifiers (as
30
35
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.
31
41
"""
32
42
33
- def __new__ (cls , code , scope = None ):
43
+ def __new__ (cls , code , scope = None , ** kwargs ):
34
44
if not isinstance (code , basestring ):
35
45
raise TypeError ("code must be an instance of basestring" )
36
46
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
-
45
47
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
+
47
61
return self
48
62
49
63
@property
0 commit comments