As we use #
for inserting comments in Python, then how does Python takes:
# -*- coding: utf-8 -*-
differently?
Yes, it is also a comment. And the contents of that comment carry special meaning if located at the top of the file, in the first two lines. From the Encoding declarations documentation:
Note that it doesn't matter what codec should be used to read the file, as far as comments are concerned. Python would normally ignore everything after the Given that the comment is required to be either the first or second in the file (and if it is the second line, the first line must be a comment too), this is entirely safe, as the configured codec can only make a difference to non-comment lines anyway. |
|||||||||||||||||||||
|
See encoding declarations in the Python Reference Manual:
(Emphasis mine) So yes, it is a comment, a special one. It is special in that the parser will try and act on it and not ignore it as it does for comments not in the first or second line. Take, for example, an unregistered encoding declaration in a sample file
If you try and run this, Python will try and process it, fail and complain:
|
|||||||||||||
|
-*-
parts are completely optional, as far as Python is concerned, but including them seems to be customary. The docs say it "is recognized also by GNU Emacs", which suggests that that's where it comes from (an example of what @tdelaney was saying about text editors), but I've seen it (and used it myself) in code that was never touched by Emacs. – Tim Pederick 8 hours ago