Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the "magic lines(s)" in python work, when specifying encoding in python file?

At the start of a python file (first line) sometimes I read

# -*- coding: utf-8 -*-

and sometimes I read

# encoding: utf-8

Both lines seem to do the same thing: specifying utf8 as encoding for all the text put in the file.

I have to questions:

  1. Why does this even work? I thought the interpreter ignores everything after a # because it invokes a comment.
  2. What is the difference between the two lines above? Does the interpreter just ignore the -*-?
like image 484
Aufwind Avatar asked May 20 '11 20:05

Aufwind


2 Answers

The two forms are equivalent. The -*- version is a special kind of comment that Emacs understands. See PEP 263 for more information.

If a comment like in either of these forms is one of the first two lines of a file, the interpreter will use the specified encoding to read the file.

like image 154
Will McCutchen Avatar answered Nov 11 '22 16:11

Will McCutchen


It works because the implementation looks for it, there is nothing magical about it. There is no difference, all possible variants are defined by PEP 263 (the only difference is that the first one is Emacs-compatible).

like image 23
Cat Plus Plus Avatar answered Nov 11 '22 16:11

Cat Plus Plus