MCPcopy Create free account
hub / github.com/dask/dask / ensure_bytes

Function ensure_bytes

dask/utils.py:1083–1122  ·  view source on GitHub ↗

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)

Source from the content-addressed store, hash-verified

1081
1082
1083def 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
1125def ensure_unicode(s) -> str:

Callers 3

test_ensure_bytesFunction · 0.90

Calls

no outgoing calls

Tested by 3

test_ensure_bytesFunction · 0.72