Coerce *s* to `str`. For Python 2: - `unicode` -> encoded to `str` - `str` -> `str` For Python 3: - `str` -> `str` - `bytes` -> decoded to `str`
(s, encoding='utf-8', errors='strict')
| 919 | |
| 920 | |
| 921 | def ensure_str(s, encoding='utf-8', errors='strict'): |
| 922 | """Coerce *s* to `str`. |
| 923 | |
| 924 | For Python 2: |
| 925 | - `unicode` -> encoded to `str` |
| 926 | - `str` -> `str` |
| 927 | |
| 928 | For Python 3: |
| 929 | - `str` -> `str` |
| 930 | - `bytes` -> decoded to `str` |
| 931 | """ |
| 932 | # Optimization: Fast return for the common case. |
| 933 | if type(s) is str: |
| 934 | return s |
| 935 | if PY2 and isinstance(s, text_type): |
| 936 | return s.encode(encoding, errors) |
| 937 | elif PY3 and isinstance(s, binary_type): |
| 938 | return s.decode(encoding, errors) |
| 939 | elif not isinstance(s, (text_type, binary_type)): |
| 940 | raise TypeError("not expecting type '%s'" % type(s)) |
| 941 | return s |
| 942 | |
| 943 | |
| 944 | def ensure_text(s, encoding='utf-8', errors='strict'): |