diff options
author | Charles-François Natali <cf.natali@gmail.com> | 2013-10-30 19:31:04 (GMT) |
---|---|---|
committer | Charles-François Natali <cf.natali@gmail.com> | 2013-10-30 19:31:04 (GMT) |
commit | 4574b49703785081262f65df59c1a630242e506f (patch) | |
tree | a6a9414b36943ae5608096e441a09c74d09e5f6a /Lib/selectors.py | |
parent | 7613542a27a03b7ade40e298aed6b3115dcad0df (diff) | |
download | cpython-4574b49703785081262f65df59c1a630242e506f.zip cpython-4574b49703785081262f65df59c1a630242e506f.tar.gz cpython-4574b49703785081262f65df59c1a630242e506f.tar.bz2 |
Issue #19172: Add a get_map() method to selectors.
Diffstat (limited to 'Lib/selectors.py')
-rw-r--r-- | Lib/selectors.py | 27 |
1 files changed, 26 insertions, 1 deletions
diff --git a/Lib/selectors.py b/Lib/selectors.py index fe027f0..3e6c2ad 100644 --- a/Lib/selectors.py +++ b/Lib/selectors.py @@ -6,7 +6,7 @@ This module allows high-level and efficient I/O multiplexing, built upon the from abc import ABCMeta, abstractmethod -from collections import namedtuple +from collections import namedtuple, Mapping import functools import select import sys @@ -44,6 +44,25 @@ SelectorKey = namedtuple('SelectorKey', ['fileobj', 'fd', 'events', 'data']) selected event mask and attached data.""" +class _SelectorMapping(Mapping): + """Mapping of file objects to selector keys.""" + + def __init__(self, selector): + self._selector = selector + + def __len__(self): + return len(self._selector._fd_to_key) + + def __getitem__(self, fileobj): + try: + return self._selector._fd_to_key[_fileobj_to_fd(fileobj)] + except KeyError: + raise KeyError("{!r} is not registered".format(fileobj)) from None + + def __iter__(self): + return iter(self._selector._fd_to_key) + + class BaseSelector(metaclass=ABCMeta): """Base selector class. @@ -62,6 +81,8 @@ class BaseSelector(metaclass=ABCMeta): def __init__(self): # this maps file descriptors to keys self._fd_to_key = {} + # read-only mapping returned by get_map() + self._map = _SelectorMapping(self) def register(self, fileobj, events, data=None): """Register a file object. @@ -162,6 +183,10 @@ class BaseSelector(metaclass=ABCMeta): except KeyError: raise KeyError("{!r} is not registered".format(fileobj)) from None + def get_map(self): + """Return a mapping of file objects to selector keys.""" + return self._map + def __enter__(self): return self |