"Cannot use httpx for this operation, and requests is not available."
)
- with contextlib.ExitStack() as stack:
- if not session:
- if _is_httpx:
- session = stack.enter_context(
- httpx.Client(
- http1=True,
- http2=_have_http2,
- verify=verify,
- transport=transport,
- )
- )
- else:
- session = stack.enter_context(requests.sessions.Session())
-
+ if session:
+ cm = contextlib.nullcontext(session)
+ elif _is_httpx:
+ cm = httpx.Client(
+ http1=True, http2=_have_http2, verify=verify, transport=transport
+ )
+ else:
+ cm = requests.sessions.Session()
+ with cm as session:
if transport_adapter:
session.mount(url, transport_adapter)
where, port, source, source_port
)
(begin_time, expiration) = _compute_times(timeout)
- with contextlib.ExitStack() as stack:
- if sock:
- s = sock
- else:
- s = stack.enter_context(_make_socket(af, socket.SOCK_DGRAM, source))
+ if sock:
+ cm = contextlib.nullcontext(sock)
+ else:
+ cm = _make_socket(af, socket.SOCK_DGRAM, source)
+ with cm as s:
send_udp(s, wire, destination, expiration)
(r, received_time) = receive_udp(
s,
wire = q.to_wire()
(begin_time, expiration) = _compute_times(timeout)
- with contextlib.ExitStack() as stack:
- if sock:
- s = sock
- else:
- (af, destination, source) = _destination_and_source(
- where, port, source, source_port
- )
- s = stack.enter_context(_make_socket(af, socket.SOCK_STREAM, source))
+ if sock:
+ cm = contextlib.nullcontext(sock)
+ else:
+ (af, destination, source) = _destination_and_source(
+ where, port, source, source_port
+ )
+ cm = _make_socket(af, socket.SOCK_STREAM, source)
+ with cm as s:
+ if not sock:
_connect(s, destination, expiration)
send_tcp(s, wire, expiration)
(r, received_time) = receive_tcp(
"""
- with contextlib.ExitStack() as stack:
- if isinstance(f, str):
- try:
- f = stack.enter_context(open(f))
- except OSError:
- # /etc/resolv.conf doesn't exist, can't be read, etc.
- raise NoResolverConfiguration(f"cannot open {f}")
-
+ if isinstance(f, str):
+ try:
+ cm = open(f)
+ except OSError:
+ # /etc/resolv.conf doesn't exist, can't be read, etc.
+ raise NoResolverConfiguration(f"cannot open {f}")
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
for l in f:
if len(l) == 0 or l[0] == "#" or l[0] == ";":
continue
one.
"""
- with contextlib.ExitStack() as stack:
- if isinstance(f, str):
- f = stack.enter_context(open(f, "wb"))
-
+ if isinstance(f, str):
+ cm = open(f, "wb")
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
# must be in this way, f.encoding may contain None, or even
# attribute may not be there
file_enc = getattr(f, "encoding", None)
Returns a subclass of ``dns.zone.Zone``.
"""
- with contextlib.ExitStack() as stack:
- if isinstance(f, str):
- if filename is None:
- filename = f
- f = stack.enter_context(open(f))
+ if isinstance(f, str):
+ if filename is None:
+ filename = f
+ cm = open(f)
+ else:
+ cm = contextlib.nullcontext(f)
+ with cm as f:
return from_text(
f,
origin,