Skip to content

Commit

Permalink
Make Headers.keys(), Headers.values() and Headers.items() return set-…
Browse files Browse the repository at this point in the history
…like views (#1114)
  • Loading branch information
florimondmanca authored Aug 1, 2020
1 parent a110072 commit a928421
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 14 deletions.
24 changes: 13 additions & 11 deletions httpx/_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -405,23 +405,25 @@ def raw(self) -> typing.List[typing.Tuple[bytes, bytes]]:
"""
return self._list

def keys(self) -> typing.List[str]: # type: ignore
return [key.decode(self.encoding) for key in self._dict.keys()]
def keys(self) -> typing.KeysView[str]:
return {key.decode(self.encoding): None for key in self._dict.keys()}.keys()

def values(self) -> typing.List[str]: # type: ignore
return [value.decode(self.encoding) for value in self._dict.values()]
def values(self) -> typing.ValuesView[str]:
return {
key: value.decode(self.encoding) for key, value in self._dict.items()
}.values()

def items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore
def items(self) -> typing.ItemsView[str, str]:
"""
Return a list of `(key, value)` pairs of headers. Concatenate headers
Return `(key, value)` items of headers. Concatenate headers
into a single comma seperated value when a key occurs multiple times.
"""
return [
(key.decode(self.encoding), value.decode(self.encoding))
return {
key.decode(self.encoding): value.decode(self.encoding)
for key, value in self._dict.items()
]
}.items()

def multi_items(self) -> typing.List[typing.Tuple[str, str]]: # type: ignore
def multi_items(self) -> typing.List[typing.Tuple[str, str]]:
"""
Return a list of `(key, value)` pairs of headers. Allow multiple
occurences of the same key without concatenating into a single
Expand Down Expand Up @@ -470,7 +472,7 @@ def update(self, headers: HeaderTypes = None) -> None: # type: ignore
self[header] = headers[header]

def copy(self) -> "Headers":
return Headers(self.items(), encoding=self.encoding)
return Headers(dict(self.items()), encoding=self.encoding)

def __getitem__(self, key: str) -> str:
"""
Expand Down
6 changes: 3 additions & 3 deletions tests/models/test_headers.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,9 +14,9 @@ def test_headers():
assert h.get("a") == "123, 456"
assert h.get("nope", default=None) is None
assert h.get_list("a") == ["123", "456"]
assert h.keys() == ["a", "b"]
assert h.values() == ["123, 456", "789"]
assert h.items() == [("a", "123, 456"), ("b", "789")]
assert list(h.keys()) == ["a", "b"]
assert list(h.values()) == ["123, 456", "789"]
assert list(h.items()) == [("a", "123, 456"), ("b", "789")]
assert h.multi_items() == [("a", "123"), ("a", "456"), ("b", "789")]
assert list(h) == ["a", "b"]
assert dict(h) == {"a": "123, 456", "b": "789"}
Expand Down

0 comments on commit a928421

Please sign in to comment.