Skip to content

Instantly share code, notes, and snippets.

@headsrooms
Last active November 11, 2017 16:38
Show Gist options
  • Select an option

  • Save headsrooms/c9b8d8d75cb84958572bf7c390216e02 to your computer and use it in GitHub Desktop.

Select an option

Save headsrooms/c9b8d8d75cb84958572bf7c390216e02 to your computer and use it in GitHub Desktop.
Helper functions to convert between str and bytes extracted from "Effective Python" by Brett Slatkin. Added type hints and bytearray support.
def to_str(bytes_or_str: Union[str, bytes]) -> str:
if isinstance(bytes_or_str, bytes):
value = bytes_or_str.decode('utf-8')
elif isinstance(bytes_or_str, bytearray):
value = bytes(bytes_or_str).decode('utf-8')
else:
value = bytes_or_str
return value
def to_bytes(bytes_or_str: Union[str, bytes]) -> bytes:
if isinstance(bytes_or_str, str):
value = bytes_or_str.encode('utf-8')
elif isinstance(bytes_or_str, bytearray):
value = bytes(bytes_or_str)
else:
value = bytes_or_str
return value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment