Sample

pyint-a4e668f13f61-I01

Remove comments and docstrings

Matched original source

Lines455

Scores

MethodScoreScale
Posnett00–1; higher is more readable
Dorn0.0090–1; higher is more readable
Mi0.5040–1; higher is more readable
LLOC198Logical lines; fewer is more readable
DeepSeek V4 Pro15.670–20; mean of three runs
GPT-6.1 Sol150–20; mean of three runs
BTTF0.3990–1; higher is more readable

Views

Source code

from __future__ import annotations import os.path import socket import typing import warnings from typing import Any from urllib3.exceptions import ( ClosedPoolError, ConnectTimeoutError, LocationValueError, MaxRetryError, NewConnectionError, ProtocolError, ReadTimeoutError, ResponseError, ) from urllib3.exceptions import HTTPError as _HTTPError from urllib3.exceptions import InvalidHeader as _InvalidHeader from urllib3.exceptions import ProxyError as _ProxyError from urllib3.exceptions import SSLError as _SSLError from urllib3.poolmanager import PoolManager, proxy_from_url from urllib3.util import Timeout as TimeoutSauce from urllib3.util import parse_url from urllib3.util.retry import Retry from .auth import _basic_auth_str from .compat import basestring, urlparse from .cookies import extract_cookies_to_jar from .exceptions import ( ConnectionError, ConnectTimeout, InvalidHeader, InvalidProxyURL, InvalidSchema, InvalidURL, ProxyError, ReadTimeout, RetryError, SSLError, ) from .models import Response from .structures import CaseInsensitiveDict from .utils import ( DEFAULT_CA_BUNDLE_PATH, get_auth_from_url, get_encoding_from_headers, prepend_scheme_if_needed, select_proxy, urldefragauth, ) from ._types import is_prepared as _is_prepared class HTTPAdapter(BaseAdapter): __attrs__: list[str] = [ "max_retries", "config", "_pool_connections", "_pool_maxsize", "_pool_block", ] max_retries: Retry config: dict[str, Any] proxy_manager: dict[str, Any] _pool_connections: int _pool_maxsize: int _pool_block: bool poolmanager: _PoolManager def __init__( self, pool_connections: int = DEFAULT_POOLSIZE, pool_maxsize: int = DEFAULT_POOLSIZE, max_retries: int | Retry = DEFAULT_RETRIES, pool_block: bool = DEFAULT_POOLBLOCK, ) -> None: if max_retries == DEFAULT_RETRIES: self.max_retries = Retry(0, read=False) else: self.max_retries = Retry.from_int(max_retries) self.config = {} self.proxy_manager = {} super().__init__() self._pool_connections = pool_connections self._pool_maxsize = pool_maxsize self._pool_block = pool_block self.init_poolmanager(pool_connections, pool_maxsize, block=pool_block) def __getstate__(self) -> dict[str, Any]: return {attr: getattr(self, attr, None) for attr in self.__attrs__} def __setstate__(self, state: dict[str, Any]) -> None: self.proxy_manager = {} self.config = {} for attr, value in state.items(): setattr(self, attr, value) self.init_poolmanager( self._pool_connections, self._pool_maxsize, block=self._pool_block ) def init_poolmanager( self, connections: int, maxsize: int, block: bool = DEFAULT_POOLBLOCK, **pool_kwargs: Any, ) -> None: self._pool_connections = connections self._pool_maxsize = maxsize self._pool_block = block self.poolmanager = PoolManager( num_pools=connections, maxsize=maxsize, block=block, **pool_kwargs, ) def proxy_manager_for(self, proxy: str, **proxy_kwargs: Any) -> Any: if proxy in self.proxy_manager: manager = self.proxy_manager[proxy] elif proxy.lower().startswith("socks"): username, password = get_auth_from_url(proxy) manager = self.proxy_manager[proxy] = SOCKSProxyManager( proxy, username=username, password=password, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) else: proxy_headers = self.proxy_headers(proxy) manager = self.proxy_manager[proxy] = proxy_from_url( proxy, proxy_headers=proxy_headers, num_pools=self._pool_connections, maxsize=self._pool_maxsize, block=self._pool_block, **proxy_kwargs, ) return manager def cert_verify( self, conn: Any, url: str, verify: _t.VerifyType, cert: _t.CertType ) -> None: if url.lower().startswith("https") and verify: cert_loc = None if verify is not True: cert_loc = verify if not cert_loc: cert_loc = DEFAULT_CA_BUNDLE_PATH if not cert_loc or not os.path.exists(cert_loc): raise OSError( f"Could not find a suitable TLS CA certificate bundle, " f"invalid path: {cert_loc}" ) conn.cert_reqs = "CERT_REQUIRED" if not os.path.isdir(cert_loc): conn.ca_certs = cert_loc else: conn.ca_cert_dir = cert_loc else: conn.cert_reqs = "CERT_NONE" conn.ca_certs = None conn.ca_cert_dir = None if cert: if not isinstance(cert, basestring): conn.cert_file = cert[0] conn.key_file = cert[1] else: conn.cert_file = cert conn.key_file = None if conn.cert_file and not os.path.exists(conn.cert_file): raise OSError( f"Could not find the TLS certificate file, " f"invalid path: {conn.cert_file}" ) if conn.key_file and not os.path.exists(conn.key_file): raise OSError( f"Could not find the TLS key file, invalid path: {conn.key_file}" ) def build_response(self, req: PreparedRequest, resp: Any) -> Response: assert _is_prepared(req) response = Response() response.status_code = getattr(resp, "status", None) response.headers = CaseInsensitiveDict(getattr(resp, "headers", {})) response.encoding = get_encoding_from_headers(response.headers) response.raw = resp response.reason = response.raw.reason if isinstance(req.url, bytes): response.url = req.url.decode("utf-8") else: response.url = req.url extract_cookies_to_jar(response.cookies, req, resp) response.request = req response.connection = self return response def build_connection_pool_key_attributes( self, request: PreparedRequest, verify: _t.VerifyType, cert: _t.CertType = None ) -> tuple[dict[str, Any], dict[str, Any]]: return _urllib3_request_context(request, verify, cert, self.poolmanager) def get_connection_with_tls_context( self, request: PreparedRequest, verify: _t.VerifyType, proxies: dict[str, str] | None = None, cert: _t.CertType = None, ) -> HTTPConnectionPool: assert _is_prepared(request) proxy = select_proxy(request.url, proxies) try: host_params, pool_kwargs = self.build_connection_pool_key_attributes( request, verify, cert, ) except ValueError as e: raise InvalidURL(e, request=request) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_host( **host_params, pool_kwargs=pool_kwargs ) else: conn = self.poolmanager.connection_from_host( **host_params, pool_kwargs=pool_kwargs ) return conn def get_connection( self, url: str, proxies: dict[str, str] | None = None ) -> HTTPConnectionPool: warnings.warn( ( "`get_connection` has been deprecated in favor of " "`get_connection_with_tls_context`. Custom HTTPAdapter subclasses " "will need to migrate for Requests>=2.32.2. Please see " "https://github.com/psf/requests/pull/6710 for more details." ), DeprecationWarning, ) proxy = select_proxy(url, proxies) if proxy: proxy = prepend_scheme_if_needed(proxy, "http") proxy_url = parse_url(proxy) if not proxy_url.host: raise InvalidProxyURL( "Please check proxy URL. It is malformed " "and could be missing the host." ) proxy_manager = self.proxy_manager_for(proxy) conn = proxy_manager.connection_from_url(url) else: parsed = urlparse(url) url = parsed.geturl() conn = self.poolmanager.connection_from_url(url) return conn def close(self) -> None: self.poolmanager.clear() for proxy in self.proxy_manager.values(): proxy.clear() def request_url( self, request: PreparedRequest, proxies: dict[str, str] | None ) -> str: assert _is_prepared(request) proxy = select_proxy(request.url, proxies) scheme = urlparse(request.url).scheme is_proxied_http_request = proxy and scheme != "https" using_socks_proxy = False if proxy: proxy_scheme = urlparse(proxy).scheme.lower() using_socks_proxy = proxy_scheme.startswith("socks") url = request.path_url if is_proxied_http_request and not using_socks_proxy: url = urldefragauth(request.url) return url def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: pass def proxy_headers(self, proxy: str) -> dict[str, str]: headers: dict[str, str] = {} username, password = get_auth_from_url(proxy) if username: headers["Proxy-Authorization"] = _basic_auth_str(username, password) return headers def send( self, request: PreparedRequest, stream: bool = False, timeout: _t.TimeoutType = None, verify: _t.VerifyType = True, cert: _t.CertType = None, proxies: dict[str, str] | None = None, ) -> Response: assert _is_prepared(request) try: conn = self.get_connection_with_tls_context( request, verify, proxies=proxies, cert=cert ) except LocationValueError as e: raise InvalidURL(e, request=request) self.cert_verify(conn, request.url, verify, cert) url = self.request_url(request, proxies) self.add_headers( request, stream=stream, timeout=timeout, verify=verify, cert=cert, proxies=proxies, ) chunked = not (request.body is None or "Content-Length" in request.headers) if isinstance(timeout, tuple): try: connect, read = timeout resolved_timeout = TimeoutSauce(connect=connect, read=read) except ValueError: raise ValueError( f"Invalid timeout {timeout}. Pass a (connect, read) timeout tuple, " f"or a single float to set both timeouts to the same value." ) elif isinstance(timeout, TimeoutSauce): resolved_timeout = timeout else: resolved_timeout = TimeoutSauce(connect=timeout, read=timeout) try: resp = conn.urlopen( method=request.method, url=url, body=request.body, headers=request.headers, redirect=False, assert_same_host=False, preload_content=False, decode_content=False, retries=self.max_retries, timeout=resolved_timeout, chunked=chunked, ) except (ProtocolError, OSError) as err: raise ConnectionError(err, request=request) except MaxRetryError as e: if isinstance(e.reason, ConnectTimeoutError): if not isinstance(e.reason, NewConnectionError): raise ConnectTimeout(e, request=request) if isinstance(e.reason, ResponseError): raise RetryError(e, request=request) if isinstance(e.reason, _ProxyError): raise ProxyError(e, request=request) if isinstance(e.reason, _SSLError): raise SSLError(e, request=request) raise ConnectionError(e, request=request) except ClosedPoolError as e: raise ConnectionError(e, request=request) except _ProxyError as e: raise ProxyError(e) except (_SSLError, _HTTPError) as e: if isinstance(e, _SSLError): raise SSLError(e, request=request) elif isinstance(e, ReadTimeoutError): raise ReadTimeout(e, request=request) elif isinstance(e, _InvalidHeader): raise InvalidHeader(e, request=request) else: raise return self.build_response(request, resp)

Loading feature diagnosis…

Source regions

Feature contributions

Feature contributions

FeatureValueContribution
(log-odds)
Halstead volumeHow much symbolic information the code contains. It combines the total number of operators and values with the number of distinct ones.16246.769−536.143
Source linesThe number of non-empty source lines.455+182
Byte entropyHow varied the bytes in the source text are. Repeated bytes give a lower value; a more even mixture gives a higher value.4.301−6.451

Intercept 8.87 + feature contributions = -351.724 (log-odds).
Score = sigmoid(-351.724) = 0.

Feature contributions

FeatureValueContribution
(log-odds)
Comment layout frequencyHow frequently the layout switches between lines containing only comments or whitespace and lines containing code.456−15.109
Indentation frequencyHow rapidly indentation changes from line to line.455+15.001
Number layout frequencyHow rapidly the number of numeric values per line changes through the code.455−10.02
Identifier layout (vertical)How rapidly the visual pattern of identifier characters changes from top to bottom.454.91+5.949
Comment layout (horizontal)How rapidly the visual pattern of comment characters changes from left to right.0−0.804
Operator visual areaThe share of the code’s visual area occupied by operators such as +, =, and *.0.071+0.253
Identifier layout (horizontal)How rapidly the visual pattern of identifier characters changes from left to right. It measures spatial frequency, not the meaning of the names.87.923−0.059

Intercept 0.07 + feature contributions = -4.72 (log-odds).
Score = sigmoid(-4.72) = 0.009.

Score0.504
Score198
Run 1

The code shows generally good structure with clear class organization, type hints, and logical method separation. However, readability is reduced by several factors: heavy import blocks with many aliases, long methods like `cert_verify` and `send` that handle multiple concerns, deep nesting in error handling chains, and some inconsistent formatting (extra whitespace, mixed comment styles). The `send` method particularly suffers from try-except blocks spanning many lines with nested conditionals. While method names are explicit and intent is usually clear, the density of proxy/TLS/retry logic creates cognitive load. Action granularity is mostly one-action-per-line, but error handling cascades could be flattened or extracted. Reading flow is acceptable but punctuation-heavy sections and vertical sprawl reduce scannability. Overall it's professional-quality code that could benefit from refactoring the most complex methods.

Run 2

The code demonstrates good readability through clear method naming, consistent type hints, and logical organization. Structure is well-maintained with focused methods handling specific concerns (proxy managers, TLS verification, connection pooling). Nesting is generally shallow, though the send() method has multiple exception handling branches that slightly increase complexity. Intent is mostly clear - method names and docstrings (though sparse) convey purpose effectively. Code length is reasonable for the functionality but some methods like cert_verify() and send() are longer than ideal. Action granularity is good - most operations are one per line, though some exception blocks could be extracted. Reading flow is natural with logical progression from connection setup to response building. Minor deductions: some methods lack docstrings, exception handling in send() is verbose, and a few lines exceed recommended length. Overall, well-structured code with only minor readability concerns.

Run 3

The code is generally well-structured with clear method separation and type hints. However, there are several readability issues: unused imports (socket, typing), some methods with deeply nested conditionals (cert_verify has 4 levels), and long methods like send() that handle multiple concerns. The exception handling in send() creates complex nesting with multiple isinstance checks. Some comments are helpful but others are placeholders. The code follows consistent naming conventions and each logical action is mostly on its own line. The flow is natural for those familiar with HTTP adapters but may be confusing for newcomers due to the domain complexity. Overall readable but could benefit from refactoring long methods and reducing nesting depth.

Run 1

Code Structure: Responsibilities are logically separated into focused methods for pooling, proxies, TLS, response construction, and sending. Nesting: Mostly shallow, but certificate validation and exception translation introduce moderately nested branches. Clarity of intent: Descriptive method names and type hints help, while absent docstrings and undefined external names in the snippet obscure some contracts and dependencies. Code length: Much of the length reflects necessary functionality, though duplicated proxy setup and the lengthy send method could be simplified. Action granularity: Most lines perform a single action; chained assignments in proxy_manager_for are minor exceptions. Reading flow: Request preparation, execution, and response construction follow a natural sequence, but excessive blank lines, inconsistent whitespace, and extensive exception handling interrupt scanning.

Run 2

Code Structure: Responsibilities are logically divided into methods for pooling, proxies, TLS, response construction, and sending. Nesting: Mostly shallow, although certificate validation and exception translation introduce moderately nested branches. Clarity of intent: Descriptive method names and type annotations help, but missing docstrings and unexplained external names such as _t and _PoolManager reduce standalone clarity. Code length: Most methods are reasonably concise; send is lengthy, and the two connection methods duplicate proxy setup logic. Action granularity: Statements generally perform one action per line, with chained manager assignments as minor exceptions. Reading flow: Request preparation, execution, and response construction follow a natural sequence, but excessive blank lines, whitespace artifacts, and extensive exception handling interrupt the flow.

Run 3

Code Structure: Well-separated methods organize pooling, TLS verification, proxy handling, response construction, and sending, though send combines several responsibilities. Nesting: Mostly shallow, with moderate nesting in certificate validation and exception translation. Clarity of intent: Descriptive method names and type annotations help, but absent docstrings and several externally undefined names obscure context and extension hooks. Code length: Generally justified by functionality, although duplicated proxy setup and verbose exception handling add length. Action granularity: Most lines perform one action; chained manager/cache assignments are minor exceptions. Reading flow: Request preparation, execution, and response construction follow a natural sequence, but excessive blank whitespace, lengthy imports, and numerous exception branches interrupt scanning.