Skip to content
Myr

Add hasattr checks for remaining protocol isinstance checks (#7505)

Before adoption: this commit came in with the history the project adopted, so no landing records it.

authored by Nate Prewitt · committed by GitHub · parent 6f205ff · Browse files · 3 files+24 added−7 removed
This commit

State

Before adoption: this commit came in with the history the project adopted, so no landing records it.

Diff stats

3 files+24 added−7 removed

  • tests:+15 added−0 removed
  • other:+9 added−7 removed

3 files+24 added−7 removed

modified:src/requests/_types.py+5 added
27 unmodified lines
28class SupportsRead(Protocol[_T_co]):29 def read(self, length: int = ..., /) -> _T_co: ...303132def has_read(obj: Any) -> TypeIs[SupportsRead[str | bytes]]:33 """Check if obj supports read, including __getattr__ based proxies."""34 return isinstance(obj, SupportsRead) or hasattr(obj, "read")353637@runtime_checkable38class SupportsItems(Protocol[_KT_co, _VT_co]):39 def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...40
148 unmodified lines
modified:src/requests/models.py+4 added-7 removed
33 unmodified lines
34from urllib3.fields import RequestField35from urllib3.filepost import encode_multipart_formdata36from urllib3.util import parse_url3738from . import _types as _t39from ._internal_utils import to_native_string, unicode_is_ascii39from ._types import SupportsRead as _SupportsRead40from .auth import HTTPBasicAuth41from .compat import (42 JSONDecodeError,43 basestring,
42 unmodified lines
86 from http.cookiejar import CookieJar8788 from typing_extensions import Self8990 from . import _types as _t90 from .adapters import HTTPAdapter91 from .cookies import RequestsCookieJar9293#: The set of HTTP status codes that indicate an automatically
65 unmodified lines
159 """160161 if isinstance(data, (str, bytes)):162 return data164 elif isinstance(data, _SupportsRead):163 elif _t.has_read(data):164 return data165 elif hasattr(data, "__iter__"):166 result: list[tuple[bytes, bytes]] = []167 for k, vs in to_key_val_list(data):
66 unmodified lines
234 fp = v235236 if isinstance(fp, (str, bytes, bytearray)):237 fdata = fp239 # data that proxies attributes to underlying objects needs hasattr240 # defensive check for untyped callers241 elif isinstance(fp, _SupportsRead) or hasattr(fp, "read"):238 elif _t.has_read(fp):239 fdata = fp.read()240 elif fp is None: # defensive check for untyped callers241 continue242 else:
394 unmodified lines
637 (body, content_type) = self._encode_files(files, raw_data)638 else:639 if raw_data:640 body = self._encode_params(raw_data)644 if isinstance(data, basestring) or isinstance(data, _SupportsRead):641 if isinstance(data, basestring) or _t.has_read(data):642 content_type = None643 else:644 content_type = "application/x-www-form-urlencoded"645
539 unmodified lines
modified:tests/test_requests.py+15 added
1096 unmodified lines
1097 )1098 assert r.status_code == 2001099 assert r.json()["files"]["file"] == "named temp file contents\n"11001101 def test_post_getattr_proxy_read_only(self, httpbin):11021103 class ReadProxy:1104 def __init__(self):1105 self._file = io.BytesIO(b"streamed body")11061107 def __getattr__(self, name):1108 if name == "__iter__":1109 raise AttributeError(name)1110 return getattr(self._file, name)11111112 r = requests.post(httpbin("post"), data=ReadProxy())1113 assert r.status_code == 2001114 assert r.json()["data"] == "streamed body"11151116 @pytest.mark.parametrize(1117 "data",1118 (1119 {"stuff": "ëlïxr"},
1975 unmodified lines