Attempt to turn `s` into bytes. Parameters ---------- s : Any The object to be converted. Will correctly handled * str * bytes * objects implementing the buffer protocol (memoryview, ndarray, etc.) Returns ------- b : bytes Raises --
(s)
| 1081 | |
| 1082 | |
| 1083 | def ensure_bytes(s) -> bytes: |
| 1084 | """Attempt to turn `s` into bytes. |
| 1085 | |
| 1086 | Parameters |
| 1087 | ---------- |
| 1088 | s : Any |
| 1089 | The object to be converted. Will correctly handled |
| 1090 | * str |
| 1091 | * bytes |
| 1092 | * objects implementing the buffer protocol (memoryview, ndarray, etc.) |
| 1093 | |
| 1094 | Returns |
| 1095 | ------- |
| 1096 | b : bytes |
| 1097 | |
| 1098 | Raises |
| 1099 | ------ |
| 1100 | TypeError |
| 1101 | When `s` cannot be converted |
| 1102 | |
| 1103 | Examples |
| 1104 | -------- |
| 1105 | >>> ensure_bytes('123') |
| 1106 | b'123' |
| 1107 | >>> ensure_bytes(b'123') |
| 1108 | b'123' |
| 1109 | >>> ensure_bytes(bytearray(b'123')) |
| 1110 | b'123' |
| 1111 | """ |
| 1112 | if isinstance(s, bytes): |
| 1113 | return s |
| 1114 | elif hasattr(s, "encode"): |
| 1115 | return s.encode() |
| 1116 | else: |
| 1117 | try: |
| 1118 | return bytes(s) |
| 1119 | except Exception as e: |
| 1120 | raise TypeError( |
| 1121 | f"Object {s} is neither a bytes object nor can be encoded to bytes" |
| 1122 | ) from e |
| 1123 | |
| 1124 | |
| 1125 | def ensure_unicode(s) -> str: |
no outgoing calls