Similar to smart_bytes, except that lazy instances are resolved to strings, rather than kept as lazy objects. If strings_only is True, don't convert (some) non-string-like objects.
(s, encoding="utf-8", strings_only=False, errors="strict")
| 85 | |
| 86 | |
| 87 | def force_bytes(s, encoding="utf-8", strings_only=False, errors="strict"): |
| 88 | """ |
| 89 | Similar to smart_bytes, except that lazy instances are resolved to |
| 90 | strings, rather than kept as lazy objects. |
| 91 | |
| 92 | If strings_only is True, don't convert (some) non-string-like objects. |
| 93 | """ |
| 94 | # Handle the common case first for performance reasons. |
| 95 | if isinstance(s, bytes): |
| 96 | if encoding == "utf-8": |
| 97 | return s |
| 98 | else: |
| 99 | return s.decode("utf-8", errors).encode(encoding, errors) |
| 100 | if strings_only and is_protected_type(s): |
| 101 | return s |
| 102 | if isinstance(s, memoryview): |
| 103 | return bytes(s) |
| 104 | return str(s).encode(encoding, errors) |
| 105 | |
| 106 | |
| 107 | def iri_to_uri(iri): |