What is the default encoding for Python 3 source files?

The story behind the answer

The default encoding for Python 3 source files is UTF-8.

Python 3 reads program text as Unicode, and its lexical analyzer decodes source files using UTF-8 unless the file declares another supported encoding. This default was established when Python 3.0 adopted PEP 3120.

A source file may override the default with an encoding declaration, traditionally called a coding cookie, on its first or second line—for example, `# -*- coding: latin-1 -*-`. Such declarations mattered more when Python 2 commonly treated source as ASCII. In Python 3, they are mainly useful for legacy encodings or tooling requirements.

UTF-8 is the encoding of the source text, not necessarily the default encoding used when Python reads or writes ordinary files at runtime. A common mix-up is confusing source-file encoding with `sys.getdefaultencoding()` or a platform’s preferred locale encoding. Python also accepts an initial UTF-8 byte-order mark, while an undecodable source file produces a `SyntaxError`.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: