1"""Encoding parameter handling and default."""
2
3import codecs
4import locale
5from typing import Final
6
7from . import copying
8
9__all__ = ['DEFAULT_ENCODING', 'Encoding']
10
11DEFAULT_ENCODING: Final = 'utf-8'
12
13
14class Encoding(copying.CopyBase):
15 """Encoding used for input and output with ``'utf-8'`` default."""
16
17 _encoding = DEFAULT_ENCODING
18
19 def __init__(self, *, encoding: str | None = DEFAULT_ENCODING,
20 **kwargs) -> None:
21 super().__init__(**kwargs)
22
23 self.encoding = encoding
24
25 def _copy_kwargs(self, **kwargs):
26 """Return the kwargs to create a copy of the instance."""
27 return super()._copy_kwargs(encoding=self._encoding, **kwargs)
28
29 @property
30 def encoding(self) -> str:
31 """The encoding for the saved source file."""
32 return self._encoding
33
34 @encoding.setter
35 def encoding(self, encoding: str | None) -> None:
36 if encoding is None:
37 encoding = locale.getpreferredencoding()
38
39 codecs.lookup(encoding) # raise early
40 self._encoding = encoding