internlm/SWE-Fixer-Train-110K huggingface dataset:
Repository: encode/httpx

Issue:
`trust_env` has diverging defaults between `Client`  and `create_ssl_context`
Right now there's a slight discrepancy for the default value of `trust_env` for `httpx.Client()` / `httpx.AsyncClient()` and `httpx.create_ssl_context()`.

* Clients use `trust_env=True` as a default.
* `create_ssl_context` uses `trust_env=None` as a default.

In practice, it means that `Client()` has SSLKEYLOGFILE support enabled by default, while `Client(verify=create_ssl_context())` has it disabled — which is non-intuitive.

Note that `create_ssl_context()` was introduced via #996, but the defaults pre-date that PR since it was already defined on the internal `SSLConfig` class. Instead, the introduction of `trust_env=None` there actually dates back from #301 (`SSLKEYLOGFILE` support). There was actually a conversation there about this, but it remained unresolved: https://github.com/encode/httpx/pull/301#discussion_r319746133

> What would we say about setting the default to True though […]?

All references to `trust_env` use `True` as the default. This inconsistency also makes #1302 a bit less intuitive, because:

```python
import httpx

transport = httpx.HTTPTransport()

# This is NOT equivalent:
transport = httpx.HTTPTransport(ssl_context=httpx.create_ssl_context())
# Users might do this^, and expect eg SSLKEYLOGFILE to be enabled, but it won't...

# They'd need to pass an explicit `trust_env=True`...
transport = httpx.HTTPTransport(ssl_context=httpx.create_ssl_context(trust_env=True))
```

To be clear, this only affects `SSLKEYLOGFILE` support. NETRC support and env-based proxies are not affected since those are managed at the client-level, which already sets `trust_env=True`.


Discussion:

Resolving patch:
diff --git a/httpx/_config.py b/httpx/_config.py
--- a/httpx/_config.py
+++ b/httpx/_config.py
@@ -43,7 +43,7 @@ class UnsetType:
 def create_ssl_context(
     cert: CertTypes = None,
     verify: VerifyTypes = True,
-    trust_env: bool = None,
+    trust_env: bool = True,
     http2: bool = False,
 ) -> ssl.SSLContext:
     return SSLConfig(
@@ -63,7 +63,7 @@ def __init__(
         *,
         cert: CertTypes = None,
         verify: VerifyTypes = True,
-        trust_env: bool = None,
+        trust_env: bool = True,
         http2: bool = False,
     ):
         self.cert = cert


Test patch:
Repository: encode/httpx

Issue:
CertTypes `keyfile` and `password` should be Optional types.
`SSLContext.load_cert_chain` can take `None` as arguments values ([docs](https://docs.python.org/3/library/ssl.html#ssl.SSLContext.load_cert_chain)) so I guess this:
https://github.com/encode/httpx/blob/c09e61d50c8f169187cada6dbf14b89c7763c63f/httpx/_types.py#L54
should be rewritten as follows:
```python
CertTypes = Union[str, Tuple[str, Optional[str]], Tuple[str, Optional[str], Optional[str]]] 
```


Discussion:
Hi,

Sounds legit, happy to review PRs towards that. :)
Feel like a type definition like that would be more readable broken over multiple lines, so many square brackets!

Resolving patch:
diff --git a/httpx/_types.py b/httpx/_types.py
--- a/httpx/_types.py
+++ b/httpx/_types.py
@@ -51,7 +51,14 @@
 
 CookieTypes = Union["Cookies", CookieJar, Dict[str, str], List[Tuple[str, str]]]
 
-CertTypes = Union[str, Tuple[str, str], Tuple[str, str, str]]
+CertTypes = Union[
+    # certfile
+    str,
+    # (certfile, keyfile)
+    Tuple[str, Optional[str]],
+    # (certfile, keyfile, password)
+    Tuple[str, Optional[str], Optional[str]],
+]
 VerifyTypes = Union[str, bool, ssl.SSLContext]
 TimeoutTypes = Union[
     Optional[float],


Test patch:
Repository: encode/httpx

Issue:
Update h2 pin?
### Discussed in https://github.com/encode/httpx/discussions/1485

<div type='discussions-op-text'>

<sup>Originally posted by **HarrySky** February 24, 2021</sup>
Hi, some time ago `h2` pin was updated in `httpcore`: https://github.com/encode/httpcore/pull/208

But it is still pinned to `3.*` in this package's `http2` extra:
https://github.com/encode/httpx/blob/0f280af8b170ed5cc48c12a894f71a8b5762f748/setup.py#L65

This is not an issue, as I can just add `h2>=3,<5` to my setup.py instead of using `httpx[http2]`, but maybe you want dependencies to be in sync with `httpcore`.

EDIT: Using git blame we can see that before `http2` extra - `httpcore[http2]` was used instead of `h2` dependency directly.</div>


Discussion:
Running into this conflict now with aioapns which wants 4.*

Resolving patch:
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -63,7 +63,7 @@ def get_packages(package):
         "async_generator; python_version < '3.7'"
     ],
     extras_require={
-        "http2": "h2==3.*",
+        "http2": "h2>=3,<5",
         "brotli": "brotlicffi==1.*",
     },
     classifiers=[


Test patch:
Repository: encode/httpx

Issue:
When using proxy the request downgrades to HTTP/1
Using the following code

```
client = httpx.Client(http2=True, proxies=proxies)
 response = client.get('https://www.truepeoplesearch.com/results?name=John', headers=headers)
response.http_version
```

It appears that it returns HTTP/1

but if I were to make the same request without proxy, it shows HTTP/2


Version of HTTPX being used.
```
Name: httpx
Version: 0.21.1
Summary: The next generation HTTP client.
Home-page: https://github.com/encode/httpx
Author: Tom Christie
Author-email: tom@tomchristie.com
```


Discussion:

Resolving patch:
diff --git a/httpx/_transports/default.py b/httpx/_transports/default.py
--- a/httpx/_transports/default.py
+++ b/httpx/_transports/default.py
@@ -138,19 +138,36 @@ def __init__(
                 retries=retries,
             )
         else:
-            self._pool = httpcore.HTTPProxy(
-                proxy_url=httpcore.URL(
-                    scheme=proxy.url.raw_scheme,
-                    host=proxy.url.raw_host,
-                    port=proxy.url.port,
-                    target=proxy.url.raw_path,
-                ),
-                proxy_headers=proxy.headers.raw,
-                ssl_context=ssl_context,
-                max_connections=limits.max_connections,
-                max_keepalive_connections=limits.max_keepalive_connections,
-                keepalive_expiry=limits.keepalive_expiry,
-            )
+            try:
+                self._pool = httpcore.HTTPProxy(
+                    proxy_url=httpcore.URL(
+                        scheme=proxy.url.raw_scheme,
+                        host=proxy.url.raw_host,
+                        port=proxy.url.port,
+                        target=proxy.url.raw_path,
+                    ),
+                    proxy_headers=proxy.headers.raw,
+                    ssl_context=ssl_context,
+                    max_connections=limits.max_connections,
+                    max_keepalive_connections=limits.max_keepalive_connections,
+                    keepalive_expiry=limits.keepalive_expiry,
+                    http1=http1,
+                    http2=http2,
+                )
+            except TypeError:  # pragma: nocover
+                self._pool = httpcore.HTTPProxy(
+                    proxy_url=httpcore.URL(
+                        scheme=proxy.url.raw_scheme,
+                        host=proxy.url.raw_host,
+                        port=proxy.url.port,
+                        target=proxy.url.raw_path,
+                    ),
+                    proxy_headers=proxy.headers.raw,
+                    ssl_context=ssl_context,
+                    max_connections=limits.max_connections,
+                    max_keepalive_connections=limits.max_keepalive_connections,
+                    keepalive_expiry=limits.keepalive_expiry,
+                )
 
     def __enter__(self: T) -> T:  # Use generics for subclass support.
         self._pool.__enter__()


Test patch:
Repository: encode/httpx

Issue:
httpx cli --proxy and --proxies option problem
The `httpx --help` shows `--proxy` option, but actually it accepts `--proxies` option.

- `--proxy`
  https://github.com/encode/httpx/blob/master/httpx/_main.py#L72

- `--proxies`
  https://github.com/encode/httpx/blob/master/httpx/_main.py#L379

Which is correct? Is there an undocumented change from`--proxy` to `--proxies`?



Discussion:
And is there a standalone repo of httpx cli in the history? I remember I submitted an issue but can not find it.
@guyskk AFAIK, no, httpx-cli is now integrated into this repository, with code in `httpx/_main.py`.

I assume the correct option is `proxies`, since that is what the CLI accepts and also what the Client accepts: `Client(proxies=...)`. Would you like to submit a fix?

Resolving patch:
diff --git a/httpx/_main.py b/httpx/_main.py
--- a/httpx/_main.py
+++ b/httpx/_main.py
@@ -69,7 +69,7 @@ def print_help() -> None:
     )
 
     table.add_row(
-        "--proxy [cyan]URL",
+        "--proxies [cyan]URL",
         "Send the request via a proxy. Should be the URL giving the proxy address.",
     )
 


Test patch:
Repository: encode/httpx

Issue:
Should AsyncClient accept a callable for default_encoding?
https://github.com/encode/httpx/blob/89cdd903b2f339c6ae319773c31b8c9352bd9cd8/httpx/_client.py#L1366

According to the online docs, the AsyncClient should also accept a callable in the form of `(bytes) -> str` for the `default_encoding` keyword parameter. The signature, linked above, only accepts a `str`.

Should the AsyncClient accept a callable like `httpx.Client` does? If so, I'm happy to make the change and submit a PR.

Thanks!


Discussion:

Resolving patch:
diff --git a/httpx/_client.py b/httpx/_client.py
--- a/httpx/_client.py
+++ b/httpx/_client.py
@@ -1363,7 +1363,7 @@ def __init__(
         transport: typing.Optional[AsyncBaseTransport] = None,
         app: typing.Optional[typing.Callable] = None,
         trust_env: bool = True,
-        default_encoding: str = "utf-8",
+        default_encoding: typing.Union[str, typing.Callable[[bytes], str]] = "utf-8",
     ):
         super().__init__(
             auth=auth,


Test patch:
Repository: encode/httpx

Issue:
Relax `HeaderTypes` type alias definition
https://github.com/encode/httpx/blob/3aa441015820a41861bff9b0e78d787b1a4f2f68/httpx/_types.py#L46-L47

Could `Dict` be replaced with `Mapping` in this type definition?

This change would placate the type-checker when I do something like the following:

```python3
from collections.abc import Mapping
from typing import Final

_DEFAULT_HEADERS: Final[Mapping[str, str]] = {
    # ...
}
```

when my intent is that the module-level dictionary is intended to be immutable but I don't want to go so far as to write a custom frozen dictionary or wrap it in `types.MappingProxyType`.

If this is acceptable, I'm happy to open a PR for the change. I was about to open a patch but your pull request template text made me think twice because this is more than just fixing a typo despite the tiny change.

Thanks!


Discussion:

Resolving patch:
diff --git a/httpx/_models.py b/httpx/_models.py
--- a/httpx/_models.py
+++ b/httpx/_models.py
@@ -3,7 +3,7 @@
 import json as jsonlib
 import typing
 import urllib.request
-from collections.abc import MutableMapping
+from collections.abc import Mapping, MutableMapping
 from http.cookiejar import Cookie, CookieJar
 
 from ._content import ByteStream, UnattachedStream, encode_request, encode_response
@@ -65,7 +65,7 @@ def __init__(
             self._list = []  # type: typing.List[typing.Tuple[bytes, bytes, bytes]]
         elif isinstance(headers, Headers):
             self._list = list(headers._list)
-        elif isinstance(headers, dict):
+        elif isinstance(headers, Mapping):
             self._list = [
                 (
                     normalize_header_key(k, lower=False, encoding=encoding),
diff --git a/httpx/_types.py b/httpx/_types.py
--- a/httpx/_types.py
+++ b/httpx/_types.py
@@ -43,8 +43,8 @@
 
 HeaderTypes = Union[
     "Headers",
-    Dict[str, str],
-    Dict[bytes, bytes],
+    Mapping[str, str],
+    Mapping[bytes, bytes],
     Sequence[Tuple[str, str]],
     Sequence[Tuple[bytes, bytes]],
 ]


Test patch:
Repository: encode/httpx

Issue:
Revert "Update package metadata"
Reverts encode/httpx#2334

- This is an alternative to #2351, and you can find the context for this PR there.

Closes #2351.


Discussion:

Resolving patch:
diff --git a/setup.py b/setup.py
new file mode 100644
--- /dev/null
+++ b/setup.py
@@ -0,0 +1,31 @@
+import sys
+
+from setuptools import setup
+
+sys.stderr.write(
+    """
+===============================
+Unsupported installation method
+===============================
+httpx no longer supports installation with `python setup.py install`.
+Please use `python -m pip install .` instead.
+"""
+)
+sys.exit(1)
+
+
+# The below code will never execute, however GitHub is particularly
+# picky about where it finds Python packaging metadata.
+# See: https://github.com/github/feedback/discussions/6456
+#
+# To be removed once GitHub catches up.
+
+setup(
+    name="httpx",
+    install_requires=[
+        "certifi",
+        "sniffio",
+        "rfc3986[idna2008]>=1.3,<2",
+        "httpcore>=0.15.0,<0.16.0",
+    ],
+)


Test patch:
Repository: encode/httpx

Issue:
Multipart doesn't support tuple data value
This works:

```python
client.post(
    url,
    data={"foo": ("1", "2")},  # tuple
)
```

This works:

```python
client.post(
    url,
    data={"foo": ["1", "2"]},  # list
    files={"test": b"test"},
)
```

This fails:

```python
client.post(
    url,
    data={"foo": ("1", "2")},  # tuple
    files={"test": b"test"},
)
```

<details>
<summary>Traceback</summary>

```
  File "httpx/_client.py", line 356, in build_request
    return Request(
  File "httpx/_models.py", line 336, in __init__
    headers, stream = encode_request(content, data, files, json)
  File "httpx/_content.py", line 210, in encode_request
    return encode_multipart_data(data or {}, files, boundary)
  File "httpx/_content.py", line 155, in encode_multipart_data
    multipart = MultipartStream(data=data, files=files, boundary=boundary)
  File "httpx/_multipart.py", line 188, in __init__
    self.fields = list(self._iter_fields(data, files))
  File "httpx/_multipart.py", line 198, in _iter_fields
    yield DataField(name=name, value=value)
  File "httpx/_multipart.py", line 36, in __init__
    raise TypeError(
TypeError: Invalid type for value. Expected primitive type, got <class 'tuple'>: ('1', '2')
```

</details>

I guess this line:

https://github.com/encode/httpx/blob/93de1980fa77f15c6b23cbaf2422c0a812caf243/httpx/_multipart.py#L194

should be implemented in the same way as this line:

https://github.com/encode/httpx/blob/93de1980fa77f15c6b23cbaf2422c0a812caf243/httpx/_content.py#L141


Discussion:

Resolving patch:
diff --git a/httpx/_multipart.py b/httpx/_multipart.py
--- a/httpx/_multipart.py
+++ b/httpx/_multipart.py
@@ -205,7 +205,7 @@ def _iter_fields(
         self, data: dict, files: RequestFiles
     ) -> typing.Iterator[typing.Union[FileField, DataField]]:
         for name, value in data.items():
-            if isinstance(value, list):
+            if isinstance(value, (tuple, list)):
                 for item in value:
                     yield DataField(name=name, value=item)
             else:


Test patch:
Repository: encode/httpx

Issue:
Support httpcore>=0.16.0
Hi,

I have a project that uses `fastapi` and `uvicorn` which demands `h11>=0.8`. Latest version of `fastapi` changed their test suite from `requests` to `httpx`. So I had to add `httpx` to my tests requirements.

Now the problem is, that `httpx` requires `httpcore`, which since version `0.16.0` allows for `h11==0.14.0`, but the current version of `httpcore` required by `httpx` doesn't, so I end up having to downgrade the `h11==0.14.0` which I have to `0.12.0`.

Can the constraint for `httpcore` be updated to `>=0.16.0` here?


Discussion:

Resolving patch:
diff --git a/httpx/__version__.py b/httpx/__version__.py
--- a/httpx/__version__.py
+++ b/httpx/__version__.py
@@ -1,3 +1,3 @@
 __title__ = "httpx"
 __description__ = "A next generation HTTP client, for Python 3."
-__version__ = "0.23.0"
+__version__ = "0.23.1"
diff --git a/setup.py b/setup.py
--- a/setup.py
+++ b/setup.py
@@ -26,6 +26,6 @@
         "certifi",
         "sniffio",
         "rfc3986[idna2008]>=1.3,<2",
-        "httpcore>=0.15.0,<0.16.0",
+        "httpcore>=0.15.0,<0.17.0",
     ],
 )


Test patch:
Repository: encode/httpx

Issue:
httpx 0.24 documentation issue for netrc support
Thanks to @alexprengere for raising this issue... 

### Discussed in https://github.com/encode/httpx/discussions/2665

<div type='discussions-op-text'>

<sup>Originally posted by **alexprengere** April 18, 2023</sup>
From the docs: https://www.python-httpx.org/advanced/#netrc-support
```
>>> auth = httpx.NetRCAuth()
>>> client = httpx.Client(auth=auth)
```
Using that snippet will yield the error:
```
>>> httpx.NetRCAuth()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: NetRCAuth.__init__() missing 1 required positional argument: 'file'
```
Using `NetRCAuth(file=None)` fixes the issue, and produces the expected behavior, but perhaps it should be made the default value (I can open a PR).</div>

httpx 0.24 documentation issue for netrc support
Thanks to @alexprengere for raising this issue... 

### Discussed in https://github.com/encode/httpx/discussions/2665

<div type='discussions-op-text'>

<sup>Originally posted by **alexprengere** April 18, 2023</sup>
From the docs: https://www.python-httpx.org/advanced/#netrc-support
```
>>> auth = httpx.NetRCAuth()
>>> client = httpx.Client(auth=auth)
```
Using that snippet will yield the error:
```
>>> httpx.NetRCAuth()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: NetRCAuth.__init__() missing 1 required positional argument: 'file'
```
Using `NetRCAuth(file=None)` fixes the issue, and produces the expected behavior, but perhaps it should be made the default value (I can open a PR).</div>



Discussion:

Resolving patch:
diff --git a/httpx/_auth.py b/httpx/_auth.py
--- a/httpx/_auth.py
+++ b/httpx/_auth.py
@@ -147,7 +147,7 @@ class NetRCAuth(Auth):
     Use a 'netrc' file to lookup basic auth credentials based on the url host.
     """
 
-    def __init__(self, file: typing.Optional[str]):
+    def __init__(self, file: typing.Optional[str] = None):
         self._netrc_info = netrc.netrc(file)
 
     def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:


Test patch:
Repository: encode/httpx

Issue:
Add `socket_options` to `httpx.HTTPTransport`.
Since [version 0.17.2](https://github.com/encode/httpcore/pull/697#issuecomment-1559059612) the `httpcore` package has support for a `socket_options` parameter.
We should add a corresponding parameter to `httpx.HTTPTransport`, which can be passed through to the connection pool.

This will resolve the use-case raised in discussion https://github.com/encode/httpx/discussions/2635...

```python
>>> import httpx
>>> socket_options = [(socket.SOL_SOCKET, socket.SO_BINDTODEVICE, b"ETH999")]
>>> transport = httpx.HTTPTransport(socket_options=socket_options)
>>> client = httpx.Client(transport=transport)
```


Discussion:

Resolving patch:
diff --git a/httpx/_transports/default.py b/httpx/_transports/default.py
--- a/httpx/_transports/default.py
+++ b/httpx/_transports/default.py
@@ -53,6 +53,12 @@
 T = typing.TypeVar("T", bound="HTTPTransport")
 A = typing.TypeVar("A", bound="AsyncHTTPTransport")
 
+SOCKET_OPTION = typing.Union[
+    typing.Tuple[int, int, int],
+    typing.Tuple[int, int, typing.Union[bytes, bytearray]],
+    typing.Tuple[int, int, None, int],
+]
+
 
 @contextlib.contextmanager
 def map_httpcore_exceptions() -> typing.Iterator[None]:
@@ -122,6 +128,7 @@ def __init__(
         uds: typing.Optional[str] = None,
         local_address: typing.Optional[str] = None,
         retries: int = 0,
+        socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,
     ) -> None:
         ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
 
@@ -136,6 +143,7 @@ def __init__(
                 uds=uds,
                 local_address=local_address,
                 retries=retries,
+                socket_options=socket_options,
             )
         elif proxy.url.scheme in ("http", "https"):
             self._pool = httpcore.HTTPProxy(
@@ -153,6 +161,7 @@ def __init__(
                 keepalive_expiry=limits.keepalive_expiry,
                 http1=http1,
                 http2=http2,
+                socket_options=socket_options,
             )
         elif proxy.url.scheme == "socks5":
             try:
@@ -257,6 +266,7 @@ def __init__(
         uds: typing.Optional[str] = None,
         local_address: typing.Optional[str] = None,
         retries: int = 0,
+        socket_options: typing.Optional[typing.Iterable[SOCKET_OPTION]] = None,
     ) -> None:
         ssl_context = create_ssl_context(verify=verify, cert=cert, trust_env=trust_env)
 
@@ -271,6 +281,7 @@ def __init__(
                 uds=uds,
                 local_address=local_address,
                 retries=retries,
+                socket_options=socket_options,
             )
         elif proxy.url.scheme in ("http", "https"):
             self._pool = httpcore.AsyncHTTPProxy(
@@ -288,6 +299,7 @@ def __init__(
                 keepalive_expiry=limits.keepalive_expiry,
                 http1=http1,
                 http2=http2,
+                socket_options=socket_options,
             )
         elif proxy.url.scheme == "socks5":
             try:


Test patch:
Repository: encode/httpx

Issue:
Change the type of `Extensions` from `Mapping` to `MutableMapping`.
### Discussed in https://github.com/encode/httpx/discussions/2793

<div type='discussions-op-text'>

<sup>Originally posted by **karosis88** July 28, 2023</sup>
I'm working on a library that implements HTTP Caching for httpx and httpcore (it provides transports and connection pools), and I'd like to add an extension that simply indicates whether or not the response was taken from the cache.

Unfortunately, the type of extension is Mapping, so this is an error for mypy.


```python
response = httpx.Response(200)
response.extensions['my_custom_extension'] = 'something'
```

OUTPUT 
```
error: Unsupported target for indexed assignment ("Mapping[Str, Any]")  [index]
```

The solution is to simply change the extension type from `Mapping` to `MutableMapping`, allowing us to add custom extensions after the response has been created.

[See also this pr](https://github.com/karosis88/hishel/pull/4)</div>

---

I believe the only change needed is in the "_models.py" file.


Discussion:

Resolving patch:
diff --git a/httpx/_types.py b/httpx/_types.py
--- a/httpx/_types.py
+++ b/httpx/_types.py
@@ -16,6 +16,7 @@
     Iterator,
     List,
     Mapping,
+    MutableMapping,
     NamedTuple,
     Optional,
     Sequence,
@@ -87,7 +88,7 @@
 
 RequestContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
 ResponseContent = Union[str, bytes, Iterable[bytes], AsyncIterable[bytes]]
-ResponseExtensions = Mapping[str, Any]
+ResponseExtensions = MutableMapping[str, Any]
 
 RequestData = Mapping[str, Any]
 
@@ -104,7 +105,7 @@
 ]
 RequestFiles = Union[Mapping[str, FileTypes], Sequence[Tuple[str, FileTypes]]]
 
-RequestExtensions = Mapping[str, Any]
+RequestExtensions = MutableMapping[str, Any]
 
 
 class SyncByteStream:


Test patch: