Last active
November 11, 2017 16:38
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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