Skip to content

Commit

Permalink
replace contextlib.nested
Browse files Browse the repository at this point in the history
  • Loading branch information
giampaolo committed May 6, 2017
1 parent bdd5331 commit 7ae9ea8
Show file tree
Hide file tree
Showing 2 changed files with 2 additions and 52 deletions.
49 changes: 0 additions & 49 deletions psutil/_compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
"""Module which provides compatibility with older Python versions."""

import collections
import contextlib
import functools
import os
import sys
Expand Down Expand Up @@ -248,51 +247,3 @@ def _access_check(fn, mode):
if _access_check(name, mode):
return name
return None


# A backport of contextlib.nested for Python 3.
nested = getattr(contextlib, "nested", None)
if nested is None:
@contextlib.contextmanager
def nested(*managers):
"""Support multiple context managers in a single with-statement.
Code like this:
with nested(A, B, C) as (X, Y, Z):
<body>
is equivalent to this:
with A as X:
with B as Y:
with C as Z:
<body>
"""
exits = []
vars = []
exc = (None, None, None)
try:
for mgr in managers:
exit = mgr.__exit__
enter = mgr.__enter__
vars.append(enter())
exits.append(exit)
yield vars
except: # NOQA
exc = sys.exc_info()
finally:
while exits:
exit = exits.pop()
try:
if exit(*exc):
exc = (None, None, None)
except: # NOQA
exc = sys.exc_info()
if exc != (None, None, None):
# Don't rely on sys.exc_info() still containing
# the right information. Another exception may
# have been raised and caught by an exit method
# exc[1] already has the __traceback__ attribute populated
raise exc[1]
5 changes: 2 additions & 3 deletions psutil/tests/test_connections.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@
from psutil import WINDOWS
from psutil._common import pconn
from psutil._common import supports_ipv6
from psutil._compat import nested
from psutil._compat import PY3
from psutil.tests import AF_UNIX
from psutil.tests import bind_socket
Expand Down Expand Up @@ -207,7 +206,7 @@ def test_tcp(self):
addr = ("127.0.0.1", get_free_port())
assert not thisproc.connections(kind='tcp4')
server, client = tcp_socketpair(AF_INET, addr=addr)
with nested(closing(server), closing(client)):
with closing(server), closing(client):
cons = thisproc.connections(kind='tcp4')
self.assertEqual(len(cons), 2)
self.assertEqual(cons[0].status, psutil.CONN_ESTABLISHED)
Expand All @@ -223,7 +222,7 @@ def test_tcp(self):
def test_unix(self):
with unix_socket_path() as name:
server, client = unix_socketpair(name)
with nested(closing(server), closing(client)):
with closing(server), closing(client):
cons = thisproc.connections(kind='unix')
assert not (cons[0].laddr and cons[0].raddr)
assert not (cons[1].laddr and cons[1].raddr)
Expand Down

0 comments on commit 7ae9ea8

Please sign in to comment.