gh-106664: selectors: add get() method to _SelectorMapping (#106665)

It can be used to avoid raising and catching KeyError twice via __getitem__.

Co-authored-by: Inada Naoki <songofacandy@gmail.com>
This commit is contained in:
J. Nick Koston 2023-07-13 09:18:53 -10:00 committed by GitHub
parent e6e0ea0113
commit 8d2f3c36ca
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 16 additions and 5 deletions

View File

@ -66,12 +66,16 @@ class _SelectorMapping(Mapping):
def __len__(self):
return len(self._selector._fd_to_key)
def get(self, fileobj, default=None):
fd = self._selector._fileobj_lookup(fileobj)
return self._selector._fd_to_key.get(fd, default)
def __getitem__(self, fileobj):
try:
fd = self._selector._fileobj_lookup(fileobj)
return self._selector._fd_to_key[fd]
except KeyError:
raise KeyError("{!r} is not registered".format(fileobj)) from None
fd = self._selector._fileobj_lookup(fileobj)
key = self._selector._fd_to_key.get(fd)
if key is None:
raise KeyError("{!r} is not registered".format(fileobj))
return key
def __iter__(self):
return iter(self._selector._fd_to_key)

View File

@ -223,6 +223,8 @@ class BaseSelectorTestCase:
self.assertRaises(RuntimeError, s.get_key, wr)
self.assertRaises(KeyError, mapping.__getitem__, rd)
self.assertRaises(KeyError, mapping.__getitem__, wr)
self.assertEqual(mapping.get(rd), None)
self.assertEqual(mapping.get(wr), None)
def test_get_key(self):
s = self.SELECTOR()
@ -241,13 +243,17 @@ class BaseSelectorTestCase:
self.addCleanup(s.close)
rd, wr = self.make_socketpair()
sentinel = object()
keys = s.get_map()
self.assertFalse(keys)
self.assertEqual(len(keys), 0)
self.assertEqual(list(keys), [])
self.assertEqual(keys.get(rd), None)
self.assertEqual(keys.get(rd, sentinel), sentinel)
key = s.register(rd, selectors.EVENT_READ, "data")
self.assertIn(rd, keys)
self.assertEqual(key, keys.get(rd))
self.assertEqual(key, keys[rd])
self.assertEqual(len(keys), 1)
self.assertEqual(list(keys), [rd.fileno()])

View File

@ -0,0 +1 @@
:mod:`selectors`: Add ``_SelectorMapping.get()`` method and optimize ``_SelectorMapping.__getitem__()``.