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
Provenance
- Commit
6f66281- Tree
d0f7f9c- Author
Nate Prewitt <nate.prewitt@gmail.com>- Committer
GitHub <noreply@github.com>- Parent
6f205ff
3 files changed+24 added−7 removed
modified:src/requests/_types.py+5 added
27 unmodified lines28 class SupportsRead(Protocol[_T_co]):29 def read(self, length: int = ..., /) -> _T_co: ...30 31 32+def 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")35+36+37 @runtime_checkable38 class SupportsItems(Protocol[_KT_co, _VT_co]):39 def items(self) -> Iterable[tuple[_KT_co, _VT_co]]: ...40 148 unmodified linesmodified:src/requests/models.py+4 added-7 removed
33 unmodified lines34 from urllib3.fields import RequestField35 from urllib3.filepost import encode_multipart_formdata36 from urllib3.util import parse_url37 38+from . import _types as _t39 from ._internal_utils import to_native_string, unicode_is_ascii39-from ._types import SupportsRead as _SupportsRead40 from .auth import HTTPBasicAuth41 from .compat import (42 JSONDecodeError,43 basestring,42 unmodified lines86 from http.cookiejar import CookieJar87 88 from typing_extensions import Self89 90- from . import _types as _t90 from .adapters import HTTPAdapter91 from .cookies import RequestsCookieJar92 93 #: The set of HTTP status codes that indicate an automatically65 unmodified lines159 """160 161 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 lines234 fp = v235 236 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 lines637 (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 linesmodified:tests/test_requests.py+15 added
1096 unmodified lines1097 )1098 assert r.status_code == 2001099 assert r.json()["files"]["file"] == "named temp file contents\n"1100 1101+ def test_post_getattr_proxy_read_only(self, httpbin):1102+1103+ class ReadProxy:1104+ def __init__(self):1105+ self._file = io.BytesIO(b"streamed body")1106+1107+ def __getattr__(self, name):1108+ if name == "__iter__":1109+ raise AttributeError(name)1110+ return getattr(self._file, name)1111+1112+ r = requests.post(httpbin("post"), data=ReadProxy())1113+ assert r.status_code == 2001114+ assert r.json()["data"] == "streamed body"1115+1116 @pytest.mark.parametrize(1117 "data",1118 (1119 {"stuff": "ëlïxr"},1975 unmodified lines