Python 3.10+iofunction
io.text_encoding
utilities
Returns the given encoding, or for None the default text encoding: 'locale', or 'utf-8' in UTF-8 Mode; helps libraries pass encoding on correctly (3.10+).
Syntax
io.text_encoding(encoding)
It opens nothing and validates nothing: any non-empty string comes back unchanged, a misspelled codec name included, and the failure only surfaces later in open(). When encoding is None it returns the sentinel 'locale' (or 'utf-8' under UTF-8 Mode), not an actual codec name — open() knows what to do with it. Call it inside your own open() wrappers: under -X warn_default_encoding it raises EncodingWarning, and stacklevel=2 makes the warning point at your caller rather than at the wrapper.
Examples
import io
print(io.text_encoding('utf-8')) # → utf-8
print(io.text_encoding('cp1251')) # → cp1251
print(io.text_encoding('no-such-codec')) # → no-such-codec
print(io.text_encoding('utf-8', 3)) # → utf-8
print(io.text_encoding(None) in ('locale', 'utf-8')) # → True
See also
Open in the full glossarydocs.python.orgReport an inaccuracy