MCPcopy Index your code
hub / github.com/google/python-fire / EncodeToBytes

Function EncodeToBytes

fire/console/console_attr.py:757–795  ·  view source on GitHub ↗

r"""Encode data to bytes. The primary use case is for base64/mime style 7-bit ascii encoding where the encoder input must be bytes. "safe" means that the conversion always returns bytes and will not raise codec exceptions. If data is text then an 8-bit ascii encoding is attempted, then the

(data)

Source from the content-addressed store, hash-verified

755
756
757def EncodeToBytes(data):
758 r"""Encode data to bytes.
759
760 The primary use case is for base64/mime style 7-bit ascii encoding where the
761 encoder input must be bytes. "safe" means that the conversion always returns
762 bytes and will not raise codec exceptions.
763
764 If data is text then an 8-bit ascii encoding is attempted, then the console
765 encoding, and finally utf-8.
766
767 Args:
768 data: Any bytes, string, or object that has str() or unicode() methods.
769
770 Returns:
771 A bytes string representation of the data.
772 """
773 if data is None:
774 return b''
775 if isinstance(data, bytes):
776 # Already bytes - our work is done.
777 return data
778
779 # Coerce to text that will be converted to bytes.
780 s = str(data)
781
782 try:
783 # Assume the text can be directly converted to bytes (8-bit ascii).
784 return s.encode('iso-8859-1')
785 except UnicodeEncodeError:
786 pass
787
788 try:
789 # Try the output encoding.
790 return s.encode(GetConsoleAttr().GetEncoding())
791 except UnicodeEncodeError:
792 pass
793
794 # Punt to utf-8.
795 return s.encode('utf-8')
796
797
798def Decode(data, encoding=None):

Callers

nothing calls this directly

Calls 2

GetConsoleAttrFunction · 0.85
GetEncodingMethod · 0.80

Tested by

no test coverage detected