Return the binary representation of ``text``. If ``text`` is already a bytes object, return it as-is.
(
text: str | bytes, encoding: str | None = None, errors: str = "strict"
)
| 86 | |
| 87 | |
| 88 | def to_bytes( |
| 89 | text: str | bytes, encoding: str | None = None, errors: str = "strict" |
| 90 | ) -> bytes: |
| 91 | """Return the binary representation of ``text``. If ``text`` |
| 92 | is already a bytes object, return it as-is.""" |
| 93 | if isinstance(text, bytes): |
| 94 | return text |
| 95 | if not isinstance(text, str): |
| 96 | raise TypeError( |
| 97 | f"to_bytes must receive a str or bytes object, got {type(text).__name__}" |
| 98 | ) |
| 99 | if encoding is None: |
| 100 | encoding = "utf-8" |
| 101 | return text.encode(encoding, errors) |
| 102 | |
| 103 | |
| 104 | def _chunk_iter(text: str, chunk_size: int) -> Iterable[tuple[str, int]]: |
no outgoing calls