@@ -999,8 +999,18 @@ dict_update(PyObject *mp, PyObject *args)
999
999
return Py_None ;
1000
1000
}
1001
1001
1002
+ /* Update unconditionally replaces existing items.
1003
+ Merge has a 3rd argument 'override'; if set, it acts like Update,
1004
+ otherwise it leaves existing items unchanged. */
1005
+
1002
1006
int
1003
1007
PyDict_Update (PyObject * a , PyObject * b )
1008
+ {
1009
+ return PyDict_Merge (a , b , 1 );
1010
+ }
1011
+
1012
+ int
1013
+ PyDict_Merge (PyObject * a , PyObject * b , int override )
1004
1014
{
1005
1015
register PyDictObject * mp , * other ;
1006
1016
register int i ;
@@ -1031,7 +1041,9 @@ PyDict_Update(PyObject *a, PyObject *b)
1031
1041
}
1032
1042
for (i = 0 ; i <= other -> ma_mask ; i ++ ) {
1033
1043
entry = & other -> ma_table [i ];
1034
- if (entry -> me_value != NULL ) {
1044
+ if (entry -> me_value != NULL &&
1045
+ (override ||
1046
+ PyDict_GetItem (a , entry -> me_key ) == NULL )) {
1035
1047
Py_INCREF (entry -> me_key );
1036
1048
Py_INCREF (entry -> me_value );
1037
1049
insertdict (mp , entry -> me_key , entry -> me_hash ,
@@ -1060,13 +1072,17 @@ PyDict_Update(PyObject *a, PyObject *b)
1060
1072
return -1 ;
1061
1073
1062
1074
for (key = PyIter_Next (iter ); key ; key = PyIter_Next (iter )) {
1075
+ if (!override && PyDict_GetItem (a , key ) != NULL ) {
1076
+ Py_DECREF (key );
1077
+ continue ;
1078
+ }
1063
1079
value = PyObject_GetItem (b , key );
1064
1080
if (value == NULL ) {
1065
1081
Py_DECREF (iter );
1066
1082
Py_DECREF (key );
1067
1083
return -1 ;
1068
1084
}
1069
- status = PyDict_SetItem (( PyObject * ) mp , key , value );
1085
+ status = PyDict_SetItem (a , key , value );
1070
1086
Py_DECREF (key );
1071
1087
Py_DECREF (value );
1072
1088
if (status < 0 ) {
0 commit comments