Skip to content

Commit

Permalink
Add type annotations to compat.to_str() and compat.to_bytes().
Browse files Browse the repository at this point in the history
- I'm not sure if these functions are truly necessary if the library no longer supports Python 2, but the use of it with `encoding` is prevalant enough around the library that it seems worth typing.
- The overloads are necessary to account for None being a passthrough value.
 - Two cases of this are `ParseResult.copy_with()` and `ParseResultBytes.copy_with()`. The `attrs_dict` dictionary in those methods is allowed to have None, and None is allowed for all of the component parameters (from what I can tell). Thus, whether intentional or not, `compat.to_(bytes|str)()`'s ability to let values pass through without modification, so long as they aren't bytes, is depended upon.
  • Loading branch information
Sachaa-Thanasius committed Jun 15, 2024
1 parent 9df0355 commit 6c3d109
Showing 1 changed file with 29 additions and 2 deletions.
31 changes: 29 additions & 2 deletions src/rfc3986/compat.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,21 +12,48 @@
# See the License for the specific language governing permissions and
# limitations under the License.
"""Compatibility module for Python 2 and 3 support."""
import typing as t

__all__ = (
"to_bytes",
"to_str",
)


def to_str(b, encoding="utf-8"):
@t.overload
def to_str(b: t.Union[str, bytes], encoding: str = "utf-8") -> str:
...


@t.overload
def to_str(b: None, encoding: str = "utf-8") -> None:
...


def to_str(
b: t.Optional[t.Union[str, bytes]],
encoding: str = "utf-8",
) -> t.Optional[str]:
"""Ensure that b is text in the specified encoding."""
if hasattr(b, "decode") and not isinstance(b, str):
b = b.decode(encoding)
return b


def to_bytes(s, encoding="utf-8"):
@t.overload
def to_bytes(s: t.Union[str, bytes], encoding: str = "utf-8") -> bytes:
...


@t.overload
def to_bytes(s: None, encoding: str = "utf-8") -> None:
...


def to_bytes(
s: t.Optional[t.Union[str, bytes]],
encoding: str = "utf-8",
) -> t.Optional[bytes]:
"""Ensure that s is converted to bytes from the encoding."""
if hasattr(s, "encode") and not isinstance(s, bytes):
s = s.encode(encoding)
Expand Down

0 comments on commit 6c3d109

Please sign in to comment.