Should I start a py file with coding information? [duplicate]
Should I start a py file with coding information? [duplicate]
This question already has an answer here:
Can you tell me how I should formalize my .py file.
.py
From some sources I've found that all files should start with:
# coding : utf-8
# PEP-8
Some people on GitHub do this:
# -*- coding: utf-8 -*-
However, Google for example doesn't use either of these and start files with license information:
# Copyright (C) 2018 Google Inc.
# Licensed under http://www.apache.org/licenses/LICENSE-2.0 <see LICENSE file>
What is the best and accepted way?
This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.
# PEP-8
pep8
pep8
pycodestyle
1 Answer
1
It depends.
Python 2 used ASCII as default encoding for source files.
Python 3's default is UTF-8.
So, if you intend to only support Python 3+ then you don't have to declare the utf-8 encoding as it is already the default.
If you intend to support Python 2 as well and you have non-ASCII string literals then you should declare an encoding.
If your text editor also needs a coding declaration (e.g., if your Unix locale is set to, say, Latin-1, but your code is UTF-8), Python's lenient syntax allows a single declaration to be used for both—e.g., # -*- coding: utf-8 -*- is recognized by both emacs and Python.
# -*- coding: utf-8 -*-
Some official information:
Python 3's docs about unicode support: https://docs.python.org/3/howto/unicode.html#python-s-unicode-support
PEP 263 that introduced the encoding declaration syntax: https://www.python.org/dev/peps/pep-0263/
PEP 3210 about changing the default encoding from ASCII to UTF-8 starting from Python 3.0: https://www.python.org/dev/peps/pep-3120/
It might also be worth adding links to PEP 263 and PEP 3120, and maybe explaining the difference between the different coding declaration styles (basically, sharing the coding declaration between Python and emacs and/or vi).
– abarnert
Jul 2 at 18:23
Thanks, cool. How about PEP-8 line and licence?
– MAx Shvedov
Jul 2 at 18:25
@abarnert, thanks, added some references
– DeepSpace
Jul 2 at 18:28
@MAxShvedov I doubt you will find any PEP about that. It is up to personal preferences and organizational conventions.
– DeepSpace
Jul 2 at 18:29
@DeepSpace I got it, thank you again.
– MAx Shvedov
Jul 2 at 18:32
IIRC, the
# PEP-8declaration is an "opt-in" used by one of the super-checker tools that run a slew of format checkers, linters, etc., on your code, to specify that this file should be run through thepep8checker and rejected if there are any warnings. If I'm remembering right, it's probably obsolete, as (a)pep8is deprecated in favor ofpycodestyle, and (b) neither of the current up-to-date super-checkers seems to use this declaration so it's probably one of the two that are no longer maintained.– abarnert
Jul 2 at 18:39