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