A helper function to choose the text encoding. When encoding is not None, this function returns it. Otherwise, this function returns the default text encoding (i.e. "locale" or "utf-8" depends on UTF-8 mode). This function emits an EncodingWarning if *encoding* is None and
(encoding, stacklevel=2)
| 39 | |
| 40 | |
| 41 | def text_encoding(encoding, stacklevel=2): |
| 42 | """ |
| 43 | A helper function to choose the text encoding. |
| 44 | |
| 45 | When encoding is not None, this function returns it. |
| 46 | Otherwise, this function returns the default text encoding |
| 47 | (i.e. "locale" or "utf-8" depends on UTF-8 mode). |
| 48 | |
| 49 | This function emits an EncodingWarning if *encoding* is None and |
| 50 | sys.flags.warn_default_encoding is true. |
| 51 | |
| 52 | This can be used in APIs with an encoding=None parameter |
| 53 | that pass it to TextIOWrapper or open. |
| 54 | However, please consider using encoding="utf-8" for new APIs. |
| 55 | """ |
| 56 | if encoding is None: |
| 57 | if sys.flags.utf8_mode: |
| 58 | encoding = "utf-8" |
| 59 | else: |
| 60 | encoding = "locale" |
| 61 | if sys.flags.warn_default_encoding: |
| 62 | import warnings |
| 63 | warnings.warn("'encoding' argument not specified.", |
| 64 | EncodingWarning, stacklevel + 1) |
| 65 | return encoding |
| 66 | |
| 67 | |
| 68 | # Wrapper for builtins.open |