How to define source file encoding in Python

Python defaults to ASCII as standard encoding if not other encoding hints are given.  The source code encoding can be manually defined by placing encoding magic comment in first or second line of source file.

There are so many different ways to define the encoding, The requirement is that first or second line must match the following regular expression.

coding[:=]\s*([-\w.]+) 

The first group of this expression is then interpreted as encoding name. If the defined encoding is unknown to Python, an error will be raised.

Few examples

Plain text

# Python coding: utf-8

Emacs style format, with Python interpreter declaration

#!/usr/bin/python
# -*- coding: latin-1 -*-

Vim style

#!/usr/bin/python
# vim: set fileencoding=iso-8859-15 :