Skip to content

Commit 13b627c

Browse files
committed
Support for context managers in ZeroConf
1 parent 19e33a6 commit 13b627c

2 files changed

Lines changed: 23 additions & 1 deletion

File tree

zeroconf/__init__.py

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,8 @@
3535
import time
3636
import warnings
3737
from collections import OrderedDict
38-
from typing import Dict, List, Optional, Sequence, Union, cast
38+
from types import TracebackType # noqa # used in type hints
39+
from typing import Dict, List, Optional, Sequence, Type, Union, cast
3940
from typing import Any, Callable, Set, Tuple # noqa # used in type hints
4041

4142
import ifaddr
@@ -2861,3 +2862,15 @@ def close(self) -> None:
28612862
self.reaper.join()
28622863
for s in self._respond_sockets:
28632864
s.close()
2865+
2866+
def __enter__(self) -> 'Zeroconf':
2867+
return self
2868+
2869+
def __exit__(
2870+
self,
2871+
exc_type: Optional[Type[BaseException]],
2872+
exc_val: Optional[BaseException],
2873+
exc_tb: Optional[TracebackType],
2874+
) -> 'Literal[False]': # type: ignore # noqa
2875+
self.close()
2876+
return False

zeroconf/test.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -515,6 +515,15 @@ def test_launch_and_close(self):
515515
rv = r.Zeroconf(interfaces=r.InterfaceChoice.Default)
516516
rv.close()
517517

518+
def test_launch_and_close_context_manager(self):
519+
with r.Zeroconf(interfaces=r.InterfaceChoice.All) as rv:
520+
assert rv.done is False
521+
assert rv.done is True
522+
523+
with r.Zeroconf(interfaces=r.InterfaceChoice.Default) as rv:
524+
assert rv.done is False
525+
assert rv.done is True
526+
518527
@unittest.skipIf(not socket.has_ipv6, 'Requires IPv6')
519528
@unittest.skipIf(os.environ.get('SKIP_IPV6'), 'IPv6 tests disabled')
520529
def test_launch_and_close_v4_v6(self):

0 commit comments

Comments
 (0)