Python source file encoding utf 8

PEP 263 – Defining Python Source Code Encodings

This PEP proposes to introduce a syntax to declare the encoding of a Python source file. The encoding information is then used by the Python parser to interpret the file using the given encoding. Most notably this enhances the interpretation of Unicode literals in the source code and makes it possible to write Unicode literals using e.g. UTF-8 directly in an Unicode aware editor.

Problem

In Python 2.1, Unicode literals can only be written using the Latin-1 based encoding “unicode-escape”. This makes the programming environment rather unfriendly to Python users who live and work in non-Latin-1 locales such as many of the Asian countries. Programmers can write their 8-bit strings using the favorite encoding, but are bound to the “unicode-escape” encoding for Unicode literals.

Proposed Solution

I propose to make the Python source code encoding both visible and changeable on a per-source file basis by using a special comment at the top of the file to declare the encoding.

To make Python aware of this encoding declaration a number of concept changes are necessary with respect to the handling of Python source code data.

Defining the Encoding

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

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:

Читайте также:  This usage in java

or (using formats recognized by popular editors):

#!/usr/bin/python # vim: set fileencoding= : 

More precisely, the first or second line must match the following regular expression:

The first group of this expression is then interpreted as encoding name. If the encoding is unknown to Python, an error is raised during compilation. There must not be any Python statement on the line that contains the encoding declaration. If the first line matches the second line is ignored.

To aid with platforms such as Windows, which add Unicode BOM marks to the beginning of Unicode files, the UTF-8 signature \xef\xbb\xbf will be interpreted as ‘utf-8’ encoding as well (even if no magic encoding comment is given).

If a source file uses both the UTF-8 BOM mark signature and a magic encoding comment, the only allowed encoding for the comment is ‘utf-8’. Any other encoding will cause an error.

Examples

These are some examples to clarify the different styles for defining the source code encoding at the top of a Python source file:

    With interpreter binary and using Emacs style file encoding comment:

#!/usr/bin/python # -*- coding: latin-1 -*- import os, sys . #!/usr/bin/python # -*- coding: iso-8859-15 -*- import os, sys . #!/usr/bin/python # -*- coding: ascii -*- import os, sys . 
# This Python file uses the following encoding: utf-8 import os, sys . 
#!/usr/local/bin/python # coding: latin-1 import os, sys . 
#!/usr/local/bin/python import os, sys . 
#!/usr/local/bin/python # latin-1 import os, sys . 
#!/usr/local/bin/python # # -*- coding: latin-1 -*- import os, sys . 
#!/usr/local/bin/python # -*- coding: utf-42 -*- import os, sys . 

Concepts

The PEP is based on the following concepts which would have to be implemented to enable usage of such a magic comment:

  1. The complete Python source file should use a single encoding. Embedding of differently encoded data is not allowed and will result in a decoding error during compilation of the Python source code. Any encoding which allows processing the first two lines in the way indicated above is allowed as source code encoding, this includes ASCII compatible encodings as well as certain multi-byte encodings such as Shift_JIS. It does not include encodings which use two or more bytes for all characters like e.g. UTF-16. The reason for this is to keep the encoding detection algorithm in the tokenizer simple.
  2. Handling of escape sequences should continue to work as it does now, but with all possible source code encodings, that is standard string literals (both 8-bit and Unicode) are subject to escape sequence expansion while raw string literals only expand a very small subset of escape sequences.
  3. Python’s tokenizer/compiler combo will need to be updated to work as follows:
    1. read the file
    2. decode it into Unicode assuming a fixed per-file encoding
    3. convert it into a UTF-8 byte string
    4. tokenize the UTF-8 content
    5. compile it, creating Unicode objects from the given Unicode data and creating string objects from the Unicode literal data by first reencoding the UTF-8 data into 8-bit string data using the given file encoding

    Note that Python identifiers are restricted to the ASCII subset of the encoding, and thus need no further conversion after step 4.

    Implementation

    For backwards-compatibility with existing code which currently uses non-ASCII in string literals without declaring an encoding, the implementation will be introduced in two phases:

    1. Allow non-ASCII in string literals and comments, by internally treating a missing encoding declaration as a declaration of “iso-8859-1”. This will cause arbitrary byte strings to correctly round-trip between step 2 and step 5 of the processing, and provide compatibility with Python 2.2 for Unicode literals that contain non-ASCII bytes. A warning will be issued if non-ASCII bytes are found in the input, once per improperly encoded input file.
    2. Remove the warning, and change the default encoding to “ascii”.

    The builtin compile() API will be enhanced to accept Unicode as input. 8-bit string input is subject to the standard procedure for encoding detection as described above.

    If a Unicode string with a coding declaration is passed to compile() , a SyntaxError will be raised.

    SUZUKI Hisao is working on a patch; see [2] for details. A patch implementing only phase 1 is available at [1].

    Phases

    Implementation of steps 1 and 2 above were completed in 2.3, except for changing the default encoding to “ascii”.

    The default encoding was set to “ascii” in version 2.5.

    Scope

    This PEP intends to provide an upgrade path from the current (more-or-less) undefined source code encoding situation to a more robust and portable definition.

    References

    History

    • 1.10 and above: see CVS history
    • 1.8: Added ‘.’ to the coding RE.
    • 1.7: Added warnings to phase 1 implementation. Replaced the Latin-1 default encoding with the interpreter’s default encoding. Added tweaks to compile() .
    • 1.4 — 1.6: Minor tweaks
    • 1.3: Worked in comments by Martin v. Loewis: UTF-8 BOM mark detection, Emacs style magic comment, two phase approach to the implementation

    This document has been placed in the public domain.

    Источник

    10.9. File Encoding¶

    • utf-8 — a.k.a. Unicode — international standard (should be always used!)
    • iso-8859-1 — ISO standard for Western Europe and USA
    • iso-8859-2 — ISO standard for Central Europe (including Poland)
    • cp1250 or windows-1250 — Central European encoding on Windows
    • cp1251 or windows-1251 — Eastern European encoding on Windows
    • cp1252 or windows-1252 — Western European encoding on Windows
    • ASCII — ASCII characters only
    • Since Windows 10 version 1903, UTF-8 is default encoding for Notepad!

    ../../_images/files-windows2000-notepad-saveas.png../../_images/files-windows10-notepad-saveas.png../../_images/files-encoding-ascii.png ../../_images/files-encoding-unicode2.png../../_images/files-encoding-unicode3.png

    10.9.1. Str vs Bytes¶

    • That was a big change in Python 3
    • In Python 2, str was bytes
    • In Python 3, str is unicode (UTF-8)
    >>> text = 'Księżyc' >>> text 'Księżyc' 
    >>> text = b'Księżyc' Traceback (most recent call last): SyntaxError: bytes can only contain ASCII literal characters 

    Default encoding is UTF-8 . Encoding names are case insensitive. cp1250 and windows-1250 are aliases the same codec:

    >>> text = 'Księżyc' >>> >>> text.encode() b'Ksi\xc4\x99\xc5\xbcyc' >>> text.encode('utf-8') b'Ksi\xc4\x99\xc5\xbcyc' >>> text.encode('iso-8859-2') b'Ksi\xea\xbfyc' >>> text.encode('cp1250') b'Ksi\xea\xbfyc' >>> text.encode('windows-1250') b'Ksi\xea\xbfyc' 

    Note the length change while encoding:

    >>> text = 'Księżyc' >>> text 'Księżyc' >>> len(text) 7 
    >>> text = 'Księżyc'.encode() >>> text b'Ksi\xc4\x99\xc5\xbcyc' >>> len(text) 9 

    Note also, that those characters produce longer output:

    But despite being several «characters» long, the length is different:

    Here’s the output of all Polish diacritics (accented characters) with their encoding:

    >>> 'ą'.encode() b'\xc4\x85' >>> 'ć'.encode() b'\xc4\x87' >>> 'ę'.encode() b'\xc4\x99' >>> 'ł'.encode() b'\xc5\x82' >>> 'ń'.encode() b'\xc5\x84' >>> 'ó'.encode() b'\xc3\xb3' >>> 'ś'.encode() b'\xc5\x9b' >>> 'ż'.encode() b'\xc5\xbc' >>> 'ź'.encode() b'\xc5\xba' 

    Note also a different way of iterating over bytes :

    >>> text = 'Księżyc' >>> >>> for character in text: . print(character) K s i ę ż y c >>> >>> for character in text.encode(): . print(character) 75 115 105 196 153 197 188 121 99 

    10.9.2. UTF-8¶

    >>> FILE = r'/tmp/myfile.txt' >>> >>> with open(FILE, mode='w', encoding='utf-8') as file: . file.write('José Jiménez') 12 >>> >>> with open(FILE, encoding='utf-8') as file: . print(file.read()) José Jiménez 

    ../../_images/files-encoding-utf.png ../../_images/files-encoding-utf2.jpg

    10.9.3. Unicode Encode Error¶

    >>> FILE = r'/tmp/myfile.txt' >>> >>> with open(FILE, mode='w', encoding='cp1250') as file: . file.write('José Jiménez') 12 

    10.9.4. Unicode Decode Error¶

    >>> FILE = r'/tmp/myfile.txt' >>> >>> with open(FILE, mode='w', encoding='utf-8') as file: . file.write('José Jiménez') 12 >>> >>> with open(FILE, encoding='cp1250') as file: . print(file.read()) JosĂ© JimĂ©nez 

    10.9.5. Escape Characters¶

    • \r\n — is used on windows
    • \n — is used everywhere else
    • More information in Builtin Printing
    • Learn more at https://en.wikipedia.org/wiki/List_of_Unicode_characters

    ../../_images/type-machine.jpg

    Frequently used escape characters:

    • \n — New line (ENTER)
    • \t — Horizontal Tab (TAB)
    • \’ — Single quote ‘ (escape in single quoted strings)
    • \» — Double quote » (escape in double quoted strings)
    • \\ — Backslash \ (to indicate, that this is not escape char)

    Less frequently used escape characters:

    • \a — Bell (BEL)
    • \b — Backspace (BS)
    • \f — New page (FF — Form Feed)
    • \v — Vertical Tab (VT)
    • \uF680 — Character with 16-bit (2 bytes) hex value F680
    • \U0001F680 — Character with 32-bit (4 bytes) hex value 0001F680
    • \o755 — ASCII character with octal value 755
    • \x1F680 — ASCII character with hex value 1F680
    >>> a = '\U0001F9D1' # 🧑 >>> b = '\U0000200D' # '' >>> c = '\U0001F680' # 🚀 >>> >>> astronaut = a + b + c >>> print(astronaut) 🧑‍🚀 

    Источник

Оцените статью