How to define python source code encodings

Created
Modified

PEP 263

Python will default to ASCII as standard encoding if no other encoding hints are given.

PEP 263 defines how to declare Python source code encoding.

Using Coding

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

# coding=<encoding name>
# coding=utf-8
import os, sys
...

Using Formats Recognized

To define a source code encoding, a magic comment must be placed into the source files either as first or second line in the file, such as:

#!/usr/bin/python3
# -*- coding: <encoding name> -*-

or:

#!/usr/bin/python3
# vim: set fileencoding=<encoding name> :

With interpreter binary and using Emacs style file encoding comment:

#!/usr/bin/python3
# -*- coding: utf-8 -*-
import os, sys
...

Related Tags