Skip to content

Commit a9856b0

Browse files
committed
Compare winreg.HKEYType by the internal handle value
1 parent e733dc9 commit a9856b0

File tree

2 files changed

+55
-4
lines changed

2 files changed

+55
-4
lines changed

Lib/test/test_winreg.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -209,6 +209,31 @@ def _test_named_args(self, key, sub_key):
209209
access=KEY_ALL_ACCESS) as okey:
210210
self.assertTrue(okey.handle != 0)
211211

212+
def test_hkey_comparison(self):
213+
"""Test HKEY comparison by handle value rather than object identity."""
214+
key1 = OpenKey(HKEY_CURRENT_USER, None)
215+
key2 = OpenKey(HKEY_CURRENT_USER, None)
216+
217+
self.assertEqual(key1.handle, key2.handle)
218+
self.assertEqual(key1, key2)
219+
self.assertTrue(key1 == key2)
220+
self.assertFalse(key1 != key2)
221+
222+
key3 = OpenKey(HKEY_LOCAL_MACHINE, None)
223+
self.assertNotEqual(key1, key3)
224+
self.assertTrue(key1 != key3)
225+
self.assertFalse(key1 == key3)
226+
227+
# Closed keys should be equal (all have handle=0)
228+
CloseKey(key1)
229+
CloseKey(key2)
230+
CloseKey(key3)
231+
232+
self.assertEqual(key1.handle, 0)
233+
self.assertEqual(key2.handle, 0)
234+
self.assertEqual(key3.handle, 0)
235+
self.assertEqual(key2, key3)
236+
212237

213238
class LocalWinregTests(BaseWinregTests):
214239

PC/winreg.c

Lines changed: 30 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -181,13 +181,38 @@ PyHKEY_strFunc(PyObject *ob)
181181
return PyUnicode_FromFormat("<PyHKEY:%p>", pyhkey->hkey);
182182
}
183183

184-
static int
185-
PyHKEY_compareFunc(PyObject *ob1, PyObject *ob2)
184+
static PyObject *
185+
PyHKEY_richcompare(PyObject *ob1, PyObject *ob2, int op)
186186
{
187+
/* Both objects must be PyHKEY objects from the same module */
188+
if (Py_TYPE(ob1) != Py_TYPE(ob2)) {
189+
Py_RETURN_NOTIMPLEMENTED;
190+
}
191+
187192
PyHKEYObject *pyhkey1 = (PyHKEYObject *)ob1;
188193
PyHKEYObject *pyhkey2 = (PyHKEYObject *)ob2;
189-
return pyhkey1 == pyhkey2 ? 0 :
190-
(pyhkey1 < pyhkey2 ? -1 : 1);
194+
HKEY hkey1 = pyhkey1->hkey;
195+
HKEY hkey2 = pyhkey2->hkey;
196+
int result;
197+
198+
switch (op) {
199+
case Py_EQ:
200+
result = (hkey1 == hkey2);
201+
break;
202+
case Py_NE:
203+
result = (hkey1 != hkey2);
204+
break;
205+
default:
206+
/* Only support equality comparisons, not ordering */
207+
Py_RETURN_NOTIMPLEMENTED;
208+
}
209+
210+
if (result) {
211+
Py_RETURN_TRUE;
212+
}
213+
else {
214+
Py_RETURN_FALSE;
215+
}
191216
}
192217

193218
static Py_hash_t
@@ -365,6 +390,7 @@ static PyType_Slot pyhkey_type_slots[] = {
365390
{Py_tp_traverse, _PyObject_VisitType},
366391
{Py_tp_hash, PyHKEY_hashFunc},
367392
{Py_tp_str, PyHKEY_strFunc},
393+
{Py_tp_richcompare, PyHKEY_richcompare},
368394

369395
// Number protocol
370396
{Py_nb_add, PyHKEY_binaryFailureFunc},

0 commit comments

Comments
 (0)