Как читать байт код питон

от admin

Байт-код Python — назначение и использование

Если вы когда-либо писали или даже использовали Python, вы, вероятно, привыкли видеть файлы исходного кода Python; у них есть имена, заканчивающиеся на .py. Возможно, вы также видели другой тип файла с именем, оканчивающимся на .pyc, и возможно, вы слышали, что это файлы Python с "байт-кодом". И, возможно, вы слышали, что они экономят время, не позволяя Python пересматривать ваш исходный код при каждом запуске. Но помимо "о, это байт-код Python", знаете ли вы, что находится в этих файлах и как Python использует их?

Если нет, то сегодня ваш счастливый день. Я расскажу вам, что такое байт-код Python, как его использует Python для выполнения вашего кода и как знание о нем может вам помочь.

Python часто описывается как интерпретируемый язык – язык, на котором ваш исходный код переводится в нативные инструкции процессора во время работы программы, но это только частично верно. Python, как и многие интерпретируемые языки, на самом деле компилирует исходный код в набор инструкций для виртуальной машины, и интерпретатор Python является реализацией этой виртуальной машины. Этот промежуточный формат называется "байт-код".

Таким образом, эти файлы .pyc, оставленные Python, – это не просто "более быстрая" или "оптимизированная" версия вашего исходного кода; это инструкции байт-кода, которые будут выполняться виртуальной машиной Python во время работы вашей программы.

Давайте посмотрим на пример. Вот классический "Hello, World!", написанный на Python:

И вот байт-код, в который он превращается (переведенный в удобочитаемую форму):

Если вы наберете функцию hello() и используете для ее запуска интерпретатора CPython, приведенный выше листинг будет выполняться Python. Хотя это может показаться немного странным, поэтому давайте посмотрим детальнее на происходящее.

Внутри виртуальной машины Python

CPython использует виртуальную машину на основе стека. То есть он полностью ориентирован на структуры данных стека (где вы можете "протолкнуть" элемент на "вершину" структуры или "вытолкнуть" элемент с "верха").

CPython использует три типа стеков:

  1. Call stack. Это основная структура работающей программы на Python. У него есть один элемент (фрейм) для каждого в настоящее время активного вызова функции, причем нижняя часть стека является точкой входа в программу. Каждый вызов функции помещает новый кадр в стек вызовов, и каждый раз, когда возвращается вызов функции, его фрейм удаляется.
  2. В каждом фрейме есть evaluation stack (стек оценки), также называемый data stack. В этом стеке происходит выполнение функции Python, а выполнение кода Python состоит в основном из помещения чего-либо в этот стек, манипулирования этим и его возврата обратно.
  3. Также в каждом фрейме есть block stack. Он используется Python для отслеживания определенных типов управляющих структур: циклов, блоков try/except и т. д. Это приводит к тому, что записи помещаются в block stack, а он уже выталкивается всякий раз, когда вы выходите из одной из этих структур. Это помогает Python знать, какие блоки активны в данный момент, так что, например, оператор continue или break может воздействовать на правильный блок.

Большинство инструкций байт-кода Python манипулируют оценочным стеком текущего фрейма стека вызовов, хотя есть некоторые инструкции, которые делают другие вещи (например, переход к конкретным инструкциям или манипулирование стеком блоков).

Чтобы почувствовать это, предположим, что у нас есть некоторый код, который вызывает функцию, например: my_function (my_variable, 2). Python преобразует это в последовательность из четырех инструкций байт-кода:

  1. Инструкция LOAD_NAME, которая ищет функциональный объект my_function и помещает его в верхнюю часть стека оценки.
  2. Еще одна инструкция LOAD_NAME, которая ищет переменную my_variable и помещает ее в верхнюю часть стека оценки.
  3. Инструкция LOAD_CONST, чтобы поместить буквенное целое значение 2 поверх стека оценки.
  4. Инструкция CALL_FUNCTION.

Инструкция CALL_FUNCTION будет иметь аргумент 2, что указывает на то, что Python должен извлечь два позиционных аргумента из верхней части стека; тогда вызываемая функция будет сверху, и она также может быть выдвинута (для функций, включающих аргументы ключевых слов, используется другая инструкция – CALL_FUNCTION_KW, но с аналогичным принципом работы. Также используется третья инструкция, CALL_FUNCTION_EX, для вызовов функций, которые включают распаковку аргументов с помощью операторов * или **). Как только Python получит все это, он выделит новый фрейм в стеке вызовов, заполнит локальные переменные для вызова функции и выполнит байт-код my_function внутри этого кадра. Как только это будет сделано, кадр будет извлечен из стека вызовов, а в исходном кадре возвращаемое значение my_function будет помещено поверх стека оценки.

Доступ и понимание байт-кода Python

Если вы хотите поэкспериментировать с этим, модуль dis в стандартной библиотеке Python очень полезен; модуль dis предоставляет "дизассемблер" для байт-кода Python, что позволяет легко получить удобочитаемую версию и просмотреть различные инструкции байт-кода. Документация для модуля dis просматривает его содержимое и предоставляет полный список инструкций байт-кода, а также информацию о том, что они делают и какие аргументы они принимают.

Например, чтобы получить список байт-кодов для функции hello(), я набрал его в интерпретаторе Python и запустил:

Функция dis.dis() будет дизассемблировать функцию, метод, класс, модуль, скомпилированный объект кода Python или строковый литерал, содержащий исходный код, и напечатает понятную для человека версию. Другая удобная функция в модуле dis – это distb(). Вы можете передать ему объект трассировки Python или вызвать его после возникновения исключения, и он разберет самую верхнюю функцию в стеке вызовов во время исключения, напечатает его байт-код и вставит указатель на инструкцию, которая вызвала исключение.

Также полезно посмотреть на объекты скомпилированного кода, которые Python собирает для каждой функции, поскольку при выполнении функции используются атрибуты этих объектов кода. Например:

Объект кода доступен как атрибут __code__ в функции и содержит несколько важных атрибутов:

  • co_consts – это кортеж любых литералов, встречающихся в теле функции;
  • co_varnames – это кортеж, содержащий имена любых локальных переменных, используемых в теле функции;
  • co_names – это кортеж любых нелокальных имен, на которые есть ссылки в теле функции.

Многие инструкции байт-кода, особенно те, которые загружают значения для помещения в стек или сохраняют значения в переменных и атрибутах, – используют индексы в этих кортежах в качестве аргументов.

Итак, теперь мы можем понять список байт-кода функции hello():

  • LOAD_GLOBAL 0: говорит Python найти глобальный объект, на который ссылается имя с индексом 0 для co_names (который является функцией печати), и поместить его в стек оценки;
  • LOAD_CONST 1: принимает литеральное значение по индексу 1 co_consts и проталкивает его (значение по индексу 0 равно литералу None, которое присутствует в co_consts, поскольку вызовы функций Python имеют неявное возвращаемое значение None, если не достигнут явный оператор возврата);
  • CALL_FUNCTION 1: сообщает Python о вызове функции; ему нужно будет удалить один позиционный аргумент из стека, тогда новая вершина стека будет функцией для вызова.

"Необработанный" байт-код (как нечитаемые человеком байты) также доступен в объекте кода как атрибут co_code. Вы можете использовать список dis.opname для поиска имен инструкций байт-кода по их десятичным значениям байтов, если вы хотите попытаться вручную разобрать функцию.

Использование байт-кода

Сейчас вы наверное задаетесь вопросом: "Какова практическая ценность всей этой информации?".

Во-первых, понимание модели исполнения Python поможет вам понять ваш код. Людям нравится шутить о том, что C является своего рода "переносимым ассемблером", где вы можете догадаться, в какие машинные инструкции превратится тот или иной фрагмент исходного кода C. Понимание байт-кода даст вам те же возможности с Python. Если вы можете предвидеть, во что превращается байт-код вашего исходного кода Python, вы можете принять более правильное решение о том, как его написать и оптимизировать.

Во-вторых, понимание байт-кода – полезный способ ответить на вопросы о Python. Например, я часто вижу новых программистов на Python, которые задаются вопросом, почему одни конструкции быстрее других (например, почему <> быстрее, чем dict()). Знание того, как получить доступ и прочитать байт-код Python, позволяет вам выработать ответы (попробуйте: dis.dis("<>") или dis.dis("dict ()")).

Наконец, понимание байт-кода и того, как Python выполняет его, дает полезные знания о конкретном виде программирования, которым программисты Python нечасто занимаются, – стек-ориентированное программирование.

Python Language
Доступ к исходному коду и байт-коду Python

Интерпретатор Python компилирует код в байт-код перед выполнением его на виртуальной машине Python (см. Также « Что такое байт-код python?» .

Вот как просмотреть байт-код функции Python

Функция dis.dis в модуле dis вернет декомпилированный байт-код переданной ему функции.

Изучение объекта кода функции

CPython позволяет получить доступ к объекту кода для объекта функции.

Объект __code__ содержит исходный байт-код ( co_code ) функции, а также другую информацию, такую ​​как константы и имена переменных.

Отобразить исходный код объекта

Объекты, которые не встроены

Чтобы распечатать исходный код объекта Python, inspect . Обратите внимание, что это не будет работать для встроенных объектов или для объектов, определенных в интерактивном режиме. Для этого вам понадобятся другие методы, объясненные позже.

Погружение в пучину интерпретатора Python. Ч1

От переводчика: Наверно всем интересно, что внутри у инструмента, который используешь, этот интерес овладел и мной, но главное не утопать в нём и не закопаться так что не вылезти. Найдя для себя интересный материал, я решил заботливо перевести его и представить хабросообществу (моя первая публикация, прошу ногами сильно не пинать). Тем, кому интересен как Python работает на самом деле, прошу проследовать под кат.

Последние три месяца я потратил много времени на byterun, интерпретатор питоновского байткода, написанного на питоне. Работа над этим проектом была для меня захватывающе весёлой и познавательной. Я был бы рад, если бы вы тоже его потыкали. Но прежде нам надо немного остепенится, понять как работает python, так, чтобы мы знали, что такое интерпретатор на самом деле и с чем его едят.

Я подразумеваю, что вы сейчас в том же положении, что и я три месяца назад. Вы понимаете python, но понятия не имеете как он работает.

Небольшая заметка: Я работаю с версией 2.7 в этом посте. Третья версия почти схожа со второй, есть небольшие различия в синтаксисе и наименованиях, но в целом всё тоже самое.

Как работает python?

Мы начнём с очень (очень очень) высокого уровня внутренней работы. Что происходит когда вы выполняете код в вашем интерпретаторе?

Годы идут, ледянки тают, Линус Торвальдс пилит очередное ядро, а 64 битый процессор без устали трудится, тем временем происходит четыре шага: лексической анализ, парсинг, компиляция и наконец таки интерпретация. Парсер забирает скормленные ему инструкции и генерирует структуру которая объясняет их связь формируя AST( Абстрактное Синтаксическое Дерево). Компилятор затем преобразует AST в одни (или несколько) объектов кода (байткод + обвязка). Потом интерпретатор выполняет каждый объект.

Я не собираюсь говорить об лексическом анализе, парсинге или компиляции сегодня, наверно потому что я сам про эти вещи ни чего не знаю, но не унывайте: вы всегда сможете изучить это, потратив часов этак пятьдесят. Мы предположим, что эти шаги прошли хорошо и успешно, и у нас есть на руках объекты python кода.

Перед тем как приступить к делу, я хочу сделать небольшую ремарку: в данном топике мы будем говорить об объектах функциях, объектах кода, и байткоде. Это всё разные вещи. Давайте начнём с функций. Нам не обязательно вникать глубоко в них, чтобы добраться до интерпретатора, но я просто хочу прояснить, что объекты функции и объекты кода — это две большие разницы, а объекты функции — самые интересные.

Объекты функции

Вы наверно могли слышать про «объекты функции». Это вещи которые люди подразумевают когда говорят: «Функции — это объекты первого класса». Давайте изучим их подробнее:

«Функции это объекты первого класса» означает что функции — это объекты также как список это объект или экземпляры MyObject это объекты. Раз foo это объект, мы можем исследователь его не выполняя его (в этом и есть разница между foo() и foo). Мы можем предать foo как параметр в другую функцию или можем присвоить его переменной.

Давайте немного посмотрим на foo подробней:

Как вы можете видеть в выше приведённом коде, объект кода это атрибут объекта функции. Объект кода генерируется питоновским компилятором и интерпретатором, он содержит информацию необходимую для работы интерпретатора. Давайте посмотрим на атрибуты объекта кода:

Здесь целая куча ништяков, большинство из которых нм сейчас не нужно. Давайте подробнее рассмотрим три атрибута объекта foo.

Вот что здесь есть: имена переменных и констант которые используются в нашей функции и количество принимаемых аргументов. Но мы всё ещё не видим ни чего что было бы похоже на инструкции. Инструкции называют байткодом ссылка, кстати это атрибут объекта кода:

Напоминаю что байткод и объекты кода это не одно и тоже. Байткод это атрибут объекта кода помимо многих других атрибутов. Так что же такое байткод? Ну это просто набор байт. Они выглядят странно когда мы их печатаем потому что некоторым байтом сопоставимы символы а другим нет, давайте выведем их как числа.

Вот байты которые творят всю магию. Интерпретатор будет последовательно и безустанно выбирать байты, смотреть какие они операции выполняют и с какими аргументами и исполнять команды. Для того чтобы пойти ещё дальше можно просмотреть исходный код Cpython а конкретно ceval.c что мы сделаем позднее.

Дизассемблирование байткода

Дизассемблирование означает взять все эти байты и преобразовать их во что-нибудь, что мы человеки способны понять. Это не выполняется в стандартном цикле питона. Сегодня для этой задачи есть отличный инструмент — модуль dis. Мы воспользуемся функцией dis.dis чтобы проанализировать что делает наша foo.

Первый номер это строка исходного python кода, второй номер это смещение внутри байткода: LOAD_CONST находится на позиции 0, а STORE_FAST на позиции 3 и так далее. Средняя колонка это название самой инструкции, последние две колонки дают понятие об аргументах инструкции (ели они есть), четвертая колонка показывает сам аргумент, который представляет собой индекс в других атрибутов объекта кода. В этом примере аргумент для LOAD_CONST это индекс в списке co_consts, а аргумент для STORE_FAST это индекс в co_varnames, в пятой колонке выводятся имена переменных или значение констант. Мы можем с легкостью это проверить:

Это также объясняет вторую инструкцию STORE_FAST которая находится по позиции 3 в байткоде. Если инструкция имеет аргумент следующие два байта и есть этот аргумент. Работа интерпретатора как раз таки в том чтобы не запутается и продолжать сеять разумное, доброе, вечное. (вы могли заметить что BINARY_ADD не имеет аргументов, не волнуйтесь мы ещё вернемся к этому)

Была одна вешь которая удивляла меня когда я начел разбираться в том как работает python, как python может быть динамическим, если он ещё и «компилируется»? Обычно эти два слова «антонимы», есть динамические языки такие как Python, Ruby, и Javascript, а есть компилируемые таки как C, Java, и Haskell.

Когда люди говорят об компилируемых языках они имеют ввиду компиляцию в нативные x86/ARM/etc инструкции. Интерпретируемый язык не имеет компиляции вообще, разве что только «компилируется» на лету в байткод. Интерпретатор питона разбирает байткод и выполняет его внутри виртуальной машины, что кстати достаточно много работы, но мы поговорим об этом позднее.

Для того чтобы быть динамическим надо быть абстрактным, давайте посмотрим что это значит:

Эта дизассемблированая функция в байткоде. К тому времени как мы получаем приглашение функция modus была скомпилирована и объект корда был сгенерирован. Достаточно внезапно, но операция остатка от деления % (операция modulus) преобразуется в BINARY_MODULO. Похоже этой функцией можно воспользоваться для чисел:

Неплохо, а что если мы передадим что то другое, например строку.

Опана, что это тут? Вы наверно уже видели это раньше:

Когда операция BINARY_MODULO выполняется для двух строк она выполняет подстановку строк вместо остатка от деления. Эта ситуация отличный пример динамической типизации. Когда компилятор генерирует объект кода для modulus он не имеет понятия что такое x и y, строки ли они или числа или что-то ещё. Он просто выполняет инструкции: загрузить одну перемененную, загрузить другую, выполнять препарацию бинарного модуля, вернуть результат. Работа интерпретатора в том чтобы понимать что BINARY_MODULO значит в текущем контексте. Наша функция modulus может считать остаток, подставлять строки… может что-то ещё? Если мы определим класс с методом __mod__ то мы сможем сделать что угодно.

Одна и та же функция с одним и тем же байткодом может выполнять разные операции в зависимости от типа контекста. Также функция modulus может возбудить исключение для примера TypeError если мы вызовем его для объектов, которые не реализованы.

Это является одной из причин того, почему трудно оптимизировать python. Вы не знаете, когда вы генерируете код объекта и байт-код, что за объекты будут в конечном итоге. Russell Power и Alex Rubinsteyn написали статью «как быстр может быть python», это статья достаточного содержательная.

На сегодня пока все. Оригинал статьи тут. Прошу прошения за возможные ошибки т.к. от природы обладаю врождённой безграмотностью и вынужден пользоваться машинным способом проверки текста.

codecs — Codec registry and base classes¶

This module defines base classes for standard Python codecs (encoders and decoders) and provides access to the internal Python codec registry, which manages the codec and error handling lookup process. Most standard codecs are text encodings , which encode text to bytes (and decode bytes to text), but there are also codecs provided that encode text to text, and bytes to bytes. Custom codecs may encode and decode between arbitrary types, but some module features are restricted to be used specifically with text encodings or with codecs that encode to bytes .

The module defines the following functions for encoding and decoding with any codec:

codecs. encode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶

Encodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that encoding errors raise ValueError (or a more codec specific subclass, such as UnicodeEncodeError ). Refer to Codec Base Classes for more information on codec error handling.

codecs. decode ( obj , encoding = ‘utf-8’ , errors = ‘strict’ ) ¶

Decodes obj using the codec registered for encoding.

Errors may be given to set the desired error handling scheme. The default error handler is ‘strict’ meaning that decoding errors raise ValueError (or a more codec specific subclass, such as UnicodeDecodeError ). Refer to Codec Base Classes for more information on codec error handling.

The full details for each codec can also be looked up directly:

codecs. lookup ( encoding ) ¶

Looks up the codec info in the Python codec registry and returns a CodecInfo object as defined below.

Encodings are first looked up in the registry’s cache. If not found, the list of registered search functions is scanned. If no CodecInfo object is found, a LookupError is raised. Otherwise, the CodecInfo object is stored in the cache and returned to the caller.

class codecs. CodecInfo ( encode , decode , streamreader = None , streamwriter = None , incrementalencoder = None , incrementaldecoder = None , name = None ) ¶

Codec details when looking up the codec registry. The constructor arguments are stored in attributes of the same name:

The name of the encoding.

The stateless encoding and decoding functions. These must be functions or methods which have the same interface as the encode() and decode() methods of Codec instances (see Codec Interface ). The functions or methods are expected to work in a stateless mode.

Incremental encoder and decoder classes or factory functions. These have to provide the interface defined by the base classes IncrementalEncoder and IncrementalDecoder , respectively. Incremental codecs can maintain state.

Stream writer and reader classes or factory functions. These have to provide the interface defined by the base classes StreamWriter and StreamReader , respectively. Stream codecs can maintain state.

To simplify access to the various codec components, the module provides these additional functions which use lookup() for the codec lookup:

codecs. getencoder ( encoding ) ¶

Look up the codec for the given encoding and return its encoder function.

Raises a LookupError in case the encoding cannot be found.

codecs. getdecoder ( encoding ) ¶

Look up the codec for the given encoding and return its decoder function.

Raises a LookupError in case the encoding cannot be found.

codecs. getincrementalencoder ( encoding ) ¶

Look up the codec for the given encoding and return its incremental encoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental encoder.

codecs. getincrementaldecoder ( encoding ) ¶

Look up the codec for the given encoding and return its incremental decoder class or factory function.

Raises a LookupError in case the encoding cannot be found or the codec doesn’t support an incremental decoder.

codecs. getreader ( encoding ) ¶

Look up the codec for the given encoding and return its StreamReader class or factory function.

Raises a LookupError in case the encoding cannot be found.

codecs. getwriter ( encoding ) ¶

Look up the codec for the given encoding and return its StreamWriter class or factory function.

Raises a LookupError in case the encoding cannot be found.

Custom codecs are made available by registering a suitable codec search function:

codecs. register ( search_function ) ¶

Register a codec search function. Search functions are expected to take one argument, being the encoding name in all lower case letters with hyphens and spaces converted to underscores, and return a CodecInfo object. In case a search function cannot find a given encoding, it should return None .

Changed in version 3.9: Hyphens and spaces are converted to underscore.

Unregister a codec search function and clear the registry’s cache. If the search function is not registered, do nothing.

New in version 3.10.

While the builtin open() and the associated io module are the recommended approach for working with encoded text files, this module provides additional utility functions and classes that allow the use of a wider range of codecs when working with binary files:

codecs. open ( filename , mode = ‘r’ , encoding = None , errors = ‘strict’ , buffering = — 1 ) ¶

Open an encoded file using the given mode and return an instance of StreamReaderWriter , providing transparent encoding/decoding. The default file mode is ‘r’ , meaning to open the file in read mode.

If encoding is not None , then the underlying encoded files are always opened in binary mode. No automatic conversion of ‘\n’ is done on reading and writing. The mode argument may be any binary mode acceptable to the built-in open() function; the ‘b’ is automatically added.

encoding specifies the encoding which is to be used for the file. Any encoding that encodes to and decodes from bytes is allowed, and the data types supported by the file methods depend on the codec used.

errors may be given to define the error handling. It defaults to ‘strict’ which causes a ValueError to be raised in case an encoding error occurs.

buffering has the same meaning as for the built-in open() function. It defaults to -1 which means that the default buffer size will be used.

Changed in version 3.11: The ‘U’ mode has been removed.

Return a StreamRecoder instance, a wrapped version of file which provides transparent transcoding. The original file is closed when the wrapped version is closed.

Data written to the wrapped file is decoded according to the given data_encoding and then written to the original file as bytes using file_encoding. Bytes read from the original file are decoded according to file_encoding, and the result is encoded using data_encoding.

If file_encoding is not given, it defaults to data_encoding.

errors may be given to define the error handling. It defaults to ‘strict’ , which causes ValueError to be raised in case an encoding error occurs.

codecs. iterencode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶

Uses an incremental encoder to iteratively encode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental encoder.

This function requires that the codec accept text str objects to encode. Therefore it does not support bytes-to-bytes encoders such as base64_codec .

codecs. iterdecode ( iterator , encoding , errors = ‘strict’ , ** kwargs ) ¶

Читать:
Elenberg ht 410 как включить радио

Uses an incremental decoder to iteratively decode the input provided by iterator. This function is a generator . The errors argument (as well as any other keyword argument) is passed through to the incremental decoder.

This function requires that the codec accept bytes objects to decode. Therefore it does not support text-to-text encoders such as rot_13 , although rot_13 may be used equivalently with iterencode() .

The module also provides the following constants which are useful for reading and writing to platform dependent files:

codecs. BOM ¶ codecs. BOM_BE ¶ codecs. BOM_LE ¶ codecs. BOM_UTF8 ¶ codecs. BOM_UTF16 ¶ codecs. BOM_UTF16_BE ¶ codecs. BOM_UTF16_LE ¶ codecs. BOM_UTF32 ¶ codecs. BOM_UTF32_BE ¶ codecs. BOM_UTF32_LE ¶

These constants define various byte sequences, being Unicode byte order marks (BOMs) for several encodings. They are used in UTF-16 and UTF-32 data streams to indicate the byte order used, and in UTF-8 as a Unicode signature. BOM_UTF16 is either BOM_UTF16_BE or BOM_UTF16_LE depending on the platform’s native byte order, BOM is an alias for BOM_UTF16 , BOM_LE for BOM_UTF16_LE and BOM_BE for BOM_UTF16_BE . The others represent the BOM in UTF-8 and UTF-32 encodings.

Codec Base Classes¶

The codecs module defines a set of base classes which define the interfaces for working with codec objects, and can also be used as the basis for custom codec implementations.

Each codec has to define four interfaces to make it usable as codec in Python: stateless encoder, stateless decoder, stream reader and stream writer. The stream reader and writers typically reuse the stateless encoder/decoder to implement the file protocols. Codec authors also need to define how the codec will handle encoding and decoding errors.

Error Handlers¶

To simplify and standardize error handling, codecs may implement different error handling schemes by accepting the errors string argument:

The following error handlers can be used with all Python Standard Encodings codecs:

Raise UnicodeError (or a subclass), this is the default. Implemented in strict_errors() .

Ignore the malformed data and continue without further notice. Implemented in ignore_errors() .

Replace with a replacement marker. On encoding, use ? (ASCII character). On decoding, use � (U+FFFD, the official REPLACEMENT CHARACTER). Implemented in replace_errors() .

Replace with backslashed escape sequences. On encoding, use hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use hexadecimal form of byte value with format \xhh . Implemented in backslashreplace_errors() .

On decoding, replace byte with individual surrogate code ranging from U+DC80 to U+DCFF . This code will then be turned back into the same byte when the ‘surrogateescape’ error handler is used when encoding the data. (See PEP 383 for more.)

The following error handlers are only applicable to encoding (within text encodings ):

Replace with XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; Implemented in xmlcharrefreplace_errors() .

Replace with \N <. >escape sequences, what appears in the braces is the Name property from Unicode Character Database. Implemented in namereplace_errors() .

In addition, the following error handler is specific to the given codecs:

utf-8, utf-16, utf-32, utf-16-be, utf-16-le, utf-32-be, utf-32-le

Allow encoding and decoding surrogate code point ( U+D800 — U+DFFF ) as normal code point. Otherwise these codecs treat the presence of surrogate code point in str as an error.

New in version 3.1: The ‘surrogateescape’ and ‘surrogatepass’ error handlers.

Changed in version 3.4: The ‘surrogatepass’ error handler now works with utf-16* and utf-32* codecs.

New in version 3.5: The ‘namereplace’ error handler.

Changed in version 3.5: The ‘backslashreplace’ error handler now works with decoding and translating.

The set of allowed values can be extended by registering a new named error handler:

codecs. register_error ( name , error_handler ) ¶

Register the error handling function error_handler under the name name. The error_handler argument will be called during encoding and decoding in case of an error, when name is specified as the errors parameter.

For encoding, error_handler will be called with a UnicodeEncodeError instance, which contains information about the location of the error. The error handler must either raise this or a different exception, or return a tuple with a replacement for the unencodable part of the input and a position where encoding should continue. The replacement may be either str or bytes . If the replacement is bytes, the encoder will simply copy them into the output buffer. If the replacement is a string, the encoder will encode the replacement. Encoding continues on original input at the specified position. Negative position values will be treated as being relative to the end of the input string. If the resulting position is out of bound an IndexError will be raised.

Decoding and translating works similarly, except UnicodeDecodeError or UnicodeTranslateError will be passed to the handler and that the replacement from the error handler will be put into the output directly.

Previously registered error handlers (including the standard error handlers) can be looked up by name:

codecs. lookup_error ( name ) ¶

Return the error handler previously registered under the name name.

Raises a LookupError in case the handler cannot be found.

The following standard error handlers are also made available as module level functions:

codecs. strict_errors ( exception ) ¶

Implements the ‘strict’ error handling.

Each encoding or decoding error raises a UnicodeError .

codecs. ignore_errors ( exception ) ¶

Implements the ‘ignore’ error handling.

Malformed data is ignored; encoding or decoding is continued without further notice.

codecs. replace_errors ( exception ) ¶

Implements the ‘replace’ error handling.

Substitutes ? (ASCII character) for encoding errors or � (U+FFFD, the official REPLACEMENT CHARACTER) for decoding errors.

codecs. backslashreplace_errors ( exception ) ¶

Implements the ‘backslashreplace’ error handling.

Malformed data is replaced by a backslashed escape sequence. On encoding, use the hexadecimal form of Unicode code point with formats \xhh \uxxxx \Uxxxxxxxx . On decoding, use the hexadecimal form of byte value with format \xhh .

Changed in version 3.5: Works with decoding and translating.

Implements the ‘xmlcharrefreplace’ error handling (for encoding within text encoding only).

The unencodable character is replaced by an appropriate XML/HTML numeric character reference, which is a decimal form of Unicode code point with format &#num; .

codecs. namereplace_errors ( exception ) ¶

Implements the ‘namereplace’ error handling (for encoding within text encoding only).

The unencodable character is replaced by a \N <. >escape sequence. The set of characters that appear in the braces is the Name property from Unicode Character Database. For example, the German lowercase letter ‘ß’ will be converted to byte sequence \N .

New in version 3.5.

Stateless Encoding and Decoding¶

The base Codec class defines these methods which also define the function interfaces of the stateless encoder and decoder:

Codec. encode ( input , errors = ‘strict’ ) ¶

Encodes the object input and returns a tuple (output object, length consumed). For instance, text encoding converts a string object to a bytes object using a particular character set encoding (e.g., cp1252 or iso-8859-1 ).

The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.

The method may not store state in the Codec instance. Use StreamWriter for codecs which have to keep state in order to make encoding efficient.

The encoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Codec. decode ( input , errors = ‘strict’ ) ¶

Decodes the object input and returns a tuple (output object, length consumed). For instance, for a text encoding , decoding converts a bytes object encoded using a particular character set encoding to a string object.

For text encodings and bytes-to-bytes codecs, input must be a bytes object or one which provides the read-only buffer interface – for example, buffer objects and memory mapped files.

The errors argument defines the error handling to apply. It defaults to ‘strict’ handling.

The method may not store state in the Codec instance. Use StreamReader for codecs which have to keep state in order to make decoding efficient.

The decoder must be able to handle zero length input and return an empty object of the output object type in this situation.

Incremental Encoding and Decoding¶

The IncrementalEncoder and IncrementalDecoder classes provide the basic interface for incremental encoding and decoding. Encoding/decoding the input isn’t done with one call to the stateless encoder/decoder function, but with multiple calls to the encode() / decode() method of the incremental encoder/decoder. The incremental encoder/decoder keeps track of the encoding/decoding process during method calls.

The joined output of calls to the encode() / decode() method is the same as if all the single inputs were joined into one, and this input was encoded/decoded with the stateless encoder/decoder.

IncrementalEncoder Objects¶

The IncrementalEncoder class is used for encoding an input in multiple steps. It defines the following methods which every incremental encoder must define in order to be compatible with the Python codec registry.

class codecs. IncrementalEncoder ( errors = ‘strict’ ) ¶

Constructor for an IncrementalEncoder instance.

All incremental encoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalEncoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalEncoder object.

encode ( object , final = False ) ¶

Encodes object (taking the current state of the encoder into account) and returns the resulting encoded object. If this is the last call to encode() final must be true (the default is false).

Reset the encoder to the initial state. The output is discarded: call .encode(object, final=True) , passing an empty byte or text string if necessary, to reset the encoder and to get the output.

Return the current state of the encoder which must be an integer. The implementation should make sure that 0 is the most common state. (States that are more complicated than integers can be converted into an integer by marshaling/pickling the state and encoding the bytes of the resulting string into an integer.)

Set the state of the encoder to state. state must be an encoder state returned by getstate() .

IncrementalDecoder Objects¶

The IncrementalDecoder class is used for decoding an input in multiple steps. It defines the following methods which every incremental decoder must define in order to be compatible with the Python codec registry.

class codecs. IncrementalDecoder ( errors = ‘strict’ ) ¶

Constructor for an IncrementalDecoder instance.

All incremental decoders must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The IncrementalDecoder may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for possible values.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the IncrementalDecoder object.

decode ( object , final = False ) ¶

Decodes object (taking the current state of the decoder into account) and returns the resulting decoded object. If this is the last call to decode() final must be true (the default is false). If final is true the decoder must decode the input completely and must flush all buffers. If this isn’t possible (e.g. because of incomplete byte sequences at the end of the input) it must initiate error handling just like in the stateless case (which might raise an exception).

Reset the decoder to the initial state.

Return the current state of the decoder. This must be a tuple with two items, the first must be the buffer containing the still undecoded input. The second must be an integer and can be additional state info. (The implementation should make sure that 0 is the most common additional state info.) If this additional state info is 0 it must be possible to set the decoder to the state which has no input buffered and 0 as the additional state info, so that feeding the previously buffered input to the decoder returns it to the previous state without producing any output. (Additional state info that is more complicated than integers can be converted into an integer by marshaling/pickling the info and encoding the bytes of the resulting string into an integer.)

Set the state of the decoder to state. state must be a decoder state returned by getstate() .

Stream Encoding and Decoding¶

The StreamWriter and StreamReader classes provide generic working interfaces which can be used to implement new encoding submodules very easily. See encodings.utf_8 for an example of how this is done.

StreamWriter Objects¶

The StreamWriter class is a subclass of Codec and defines the following methods which every stream writer must define in order to be compatible with the Python codec registry.

class codecs. StreamWriter ( stream , errors = ‘strict’ ) ¶

Constructor for a StreamWriter instance.

All stream writers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for writing text or binary data, as appropriate for the specific codec.

The StreamWriter may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamWriter object.

Writes the object’s contents encoded to the stream.

Writes the concatenated iterable of strings to the stream (possibly by reusing the write() method). Infinite or very large iterables are not supported. The standard bytes-to-bytes codecs do not support this method.

Resets the codec buffers used for keeping internal state.

Calling this method should ensure that the data on the output is put into a clean state that allows appending of new fresh data without having to rescan the whole stream to recover state.

In addition to the above methods, the StreamWriter must also inherit all other methods and attributes from the underlying stream.

StreamReader Objects¶

The StreamReader class is a subclass of Codec and defines the following methods which every stream reader must define in order to be compatible with the Python codec registry.

class codecs. StreamReader ( stream , errors = ‘strict’ ) ¶

Constructor for a StreamReader instance.

All stream readers must provide this constructor interface. They are free to add additional keyword arguments, but only the ones defined here are used by the Python codec registry.

The stream argument must be a file-like object open for reading text or binary data, as appropriate for the specific codec.

The StreamReader may implement different error handling schemes by providing the errors keyword argument. See Error Handlers for the standard error handlers the underlying stream codec may support.

The errors argument will be assigned to an attribute of the same name. Assigning to this attribute makes it possible to switch between different error handling strategies during the lifetime of the StreamReader object.

The set of allowed values for the errors argument can be extended with register_error() .

read ( size = — 1 , chars = — 1 , firstline = False ) ¶

Decodes data from the stream and returns the resulting object.

The chars argument indicates the number of decoded code points or bytes to return. The read() method will never return more data than requested, but it might return less, if there is not enough available.

The size argument indicates the approximate maximum number of encoded bytes or code points to read for decoding. The decoder can modify this setting as appropriate. The default value -1 indicates to read and decode as much as possible. This parameter is intended to prevent having to decode huge files in one step.

The firstline flag indicates that it would be sufficient to only return the first line, if there are decoding errors on later lines.

The method should use a greedy read strategy meaning that it should read as much data as is allowed within the definition of the encoding and the given size, e.g. if optional encoding endings or state markers are available on the stream, these should be read too.

readline ( size = None , keepends = True ) ¶

Read one line from the input stream and return the decoded data.

size, if given, is passed as size argument to the stream’s read() method.

If keepends is false line-endings will be stripped from the lines returned.

readlines ( sizehint = None , keepends = True ) ¶

Read all lines available on the input stream and return them as a list of lines.

Line-endings are implemented using the codec’s decode() method and are included in the list entries if keepends is true.

sizehint, if given, is passed as the size argument to the stream’s read() method.

Resets the codec buffers used for keeping internal state.

Note that no stream repositioning should take place. This method is primarily intended to be able to recover from decoding errors.

In addition to the above methods, the StreamReader must also inherit all other methods and attributes from the underlying stream.

StreamReaderWriter Objects¶

The StreamReaderWriter is a convenience class that allows wrapping streams which work in both read and write modes.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs. StreamReaderWriter ( stream , Reader , Writer , errors = ‘strict’ ) ¶

Creates a StreamReaderWriter instance. stream must be a file-like object. Reader and Writer must be factory functions or classes providing the StreamReader and StreamWriter interface resp. Error handling is done in the same way as defined for the stream readers and writers.

StreamReaderWriter instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

StreamRecoder Objects¶

The StreamRecoder translates data from one encoding to another, which is sometimes useful when dealing with different encoding environments.

The design is such that one can use the factory functions returned by the lookup() function to construct the instance.

class codecs. StreamRecoder ( stream , encode , decode , Reader , Writer , errors = ‘strict’ ) ¶

Creates a StreamRecoder instance which implements a two-way conversion: encode and decode work on the frontend — the data visible to code calling read() and write() , while Reader and Writer work on the backend — the data in stream.

You can use these objects to do transparent transcodings, e.g., from Latin-1 to UTF-8 and back.

The stream argument must be a file-like object.

The encode and decode arguments must adhere to the Codec interface. Reader and Writer must be factory functions or classes providing objects of the StreamReader and StreamWriter interface respectively.

Error handling is done in the same way as defined for the stream readers and writers.

StreamRecoder instances define the combined interfaces of StreamReader and StreamWriter classes. They inherit all other methods and attributes from the underlying stream.

Encodings and Unicode¶

Strings are stored internally as sequences of code points in range U+0000 – U+10FFFF . (See PEP 393 for more details about the implementation.) Once a string object is used outside of CPU and memory, endianness and how these arrays are stored as bytes become an issue. As with other codecs, serialising a string into a sequence of bytes is known as encoding, and recreating the string from the sequence of bytes is known as decoding. There are a variety of different text serialisation codecs, which are collectivity referred to as text encodings .

The simplest text encoding (called ‘latin-1’ or ‘iso-8859-1’ ) maps the code points 0–255 to the bytes 0x0 – 0xff , which means that a string object that contains code points above U+00FF can’t be encoded with this codec. Doing so will raise a UnicodeEncodeError that looks like the following (although the details of the error message may differ): UnicodeEncodeError: ‘latin-1’ codec can’t encode character ‘\u1234’ in position 3: ordinal not in range(256) .

There’s another group of encodings (the so called charmap encodings) that choose a different subset of all Unicode code points and how these code points are mapped to the bytes 0x0 – 0xff . To see how this is done simply open e.g. encodings/cp1252.py (which is an encoding that is used primarily on Windows). There’s a string constant with 256 characters that shows you which character is mapped to which byte value.

All of these encodings can only encode 256 of the 1114112 code points defined in Unicode. A simple and straightforward way that can store each Unicode code point, is to store each code point as four consecutive bytes. There are two possibilities: store the bytes in big endian or in little endian order. These two encodings are called UTF-32-BE and UTF-32-LE respectively. Their disadvantage is that if e.g. you use UTF-32-BE on a little endian machine you will always have to swap bytes on encoding and decoding. UTF-32 avoids this problem: bytes will always be in natural endianness. When these bytes are read by a CPU with a different endianness, then bytes have to be swapped though. To be able to detect the endianness of a UTF-16 or UTF-32 byte sequence, there’s the so called BOM (“Byte Order Mark”). This is the Unicode character U+FEFF . This character can be prepended to every UTF-16 or UTF-32 byte sequence. The byte swapped version of this character ( 0xFFFE ) is an illegal character that may not appear in a Unicode text. So when the first character in a UTF-16 or UTF-32 byte sequence appears to be a U+FFFE the bytes have to be swapped on decoding. Unfortunately the character U+FEFF had a second purpose as a ZERO WIDTH NO-BREAK SPACE : a character that has no width and doesn’t allow a word to be split. It can e.g. be used to give hints to a ligature algorithm. With Unicode 4.0 using U+FEFF as a ZERO WIDTH NO-BREAK SPACE has been deprecated (with U+2060 ( WORD JOINER ) assuming this role). Nevertheless Unicode software still must be able to handle U+FEFF in both roles: as a BOM it’s a device to determine the storage layout of the encoded bytes, and vanishes once the byte sequence has been decoded into a string; as a ZERO WIDTH NO-BREAK SPACE it’s a normal character that will be decoded like any other.

There’s another encoding that is able to encode the full range of Unicode characters: UTF-8. UTF-8 is an 8-bit encoding, which means there are no issues with byte order in UTF-8. Each byte in a UTF-8 byte sequence consists of two parts: marker bits (the most significant bits) and payload bits. The marker bits are a sequence of zero to four 1 bits followed by a 0 bit. Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character):

Related Posts