45.1. Python 2 и Python 3

PL/Python поддерживает две вариации языка: Python 2 и Python 3. (Более точная информация о поддерживаемых второстепенных версиях Python может содержаться в инструкциях по установке PostgreSQL.) Так как языки Python 2 и Python 3 несовместимы в некоторых важных аспектах, во избежание смешения их в PL/Python применяется следующая схема именования:

  • Язык PostgreSQL с именем plpython2u представляет реализацию PL/Python, основанную на вариации языка Python 2.

  • Язык PostgreSQL с именем plpython3u представляет реализацию PL/Python, основанную на вариации языка Python 3.

  • Язык с именем plpythonu представляет реализацию PL/Python, основанную на версии Python по умолчанию, в данный момент это Python 2. (Этот выбор по умолчанию не зависит от того, какая версия считается локальной версией «по умолчанию», например, на какую версию указывает /usr/bin/python.) Выбор по умолчанию в отдалённом будущем выпуске PostgreSQL может быть сменён на Python 3, в зависимости от того, как будет происходить переход на Python 3 в сообществе Python.

Эта схема аналогична рекомендациям, данным в PEP 394, по выбору имени команды python и переходу с версии на версию.

Будет ли доступен PL/Python для Python 2 или для Python 3, либо сразу для обеих версий, зависит от конфигурации сборки или установленных пакетов.

Подсказка

Какая вариация будет собрана, зависит от того, как версия Python будет найдена при установке или будет задана в переменной окружения PYTHON; см. Раздел 16.4. Чтобы в одной инсталляции присутствовали обе вариации PL/Python, необходимо сконфигурировать дерево исходного кода и произвести сборку два раза.

В результате формируется такая стратегия использования и смены определённой версии:

  • Существующие пользователи и пользователи, которым в настоящее время неинтересен Python 3, могут выбрать имя языка plpythonu и им не придётся ничего менять в обозримом будущем. Чтобы упростить миграцию на Python 3, которая произойдёт в конце концов, рекомендуется постепенно проверять «готовность к будущему» кода, обновляя его до версий Python 2.6/2.7.

    На практике многие функции PL/Python можно мигрировать на Python 3 с минимальными изменениями или вовсе без изменений.

  • Пользователи, знающие, что их код очень сильно зависит от Python 2, и не планирующие когда-либо менять его, могут использовать имя языка plpython2u. Это будет работать ещё очень и очень долго, пока в PostgreSQL не будет полностью ликвидирована поддержка Python 2.

  • Пользователи, желающие погрузиться в Python 3, могут выбрать имя языка plpython3u, и их код будет работать всегда, по сегодняшним стандартам. В отдалённом будущем, когда версией по умолчанию может стать Python 3, цифру «3» из имени языка можно будет убрать из эстетических соображений.

  • Смельчаки, желающие уже сегодня получить операционное окружение только с Python 3, могут заменить содержимое управляющего файла и скриптов расширения plpythonu, чтобы все эти файлы соответствовали plpython3u. При этом надо понимать, что такая инсталляция будет несовместима с остальным миром.

Дополнительную информацию о переходе на Python 3 можно также найти в описании Что нового в Python 3.0.

Использовать PL/Python на базе Python 2 и PL/Python на базе Python 3 в одном сеансе нельзя, так как это приведёт к конфликту символов в динамических модулях, что может повлечь сбой серверного процесса PostgreSQL. В системе есть проверка, предотвращающая смешение основных версий Python в одном сеансе, которая прервёт сеанс при выявлении расхождения. Однако использовать обе вариации в одной базе данных всё же возможно, обращаясь к ним в разных сеансах.

45.1. Python 2 vs. Python 3

PL/Python supports both the Python 2 and Python 3 language variants. (The PostgreSQL installation instructions might contain more precise information about the exact supported minor versions of Python.) Because the Python 2 and Python 3 language variants are incompatible in some important aspects, the following naming and transitioning scheme is used by PL/Python to avoid mixing them:

  • The PostgreSQL language named plpython2u implements PL/Python based on the Python 2 language variant.

  • The PostgreSQL language named plpython3u implements PL/Python based on the Python 3 language variant.

  • The language named plpythonu implements PL/Python based on the default Python language variant, which is currently Python 2. (This default is independent of what any local Python installations might consider to be their default, for example, what /usr/bin/python might be.) The default will probably be changed to Python 3 in a distant future release of PostgreSQL, depending on the progress of the migration to Python 3 in the Python community.

This scheme is analogous to the recommendations in PEP 394 regarding the naming and transitioning of the python command.

It depends on the build configuration or the installed packages whether PL/Python for Python 2 or Python 3 or both are available.

Tip

The built variant depends on which Python version was found during the installation or which version was explicitly set using the PYTHON environment variable; see Section 16.4. To make both variants of PL/Python available in one installation, the source tree has to be configured and built twice.

This results in the following usage and migration strategy:

  • Existing users and users who are currently not interested in Python 3 use the language name plpythonu and don't have to change anything for the foreseeable future. It is recommended to gradually future-proof the code via migration to Python 2.6/2.7 to simplify the eventual migration to Python 3.

    In practice, many PL/Python functions will migrate to Python 3 with few or no changes.

  • Users who know that they have heavily Python 2 dependent code and don't plan to ever change it can make use of the plpython2u language name. This will continue to work into the very distant future, until Python 2 support might be completely dropped by PostgreSQL.

  • Users who want to dive into Python 3 can use the plpython3u language name, which will keep working forever by today's standards. In the distant future, when Python 3 might become the default, they might like to remove the 3 for aesthetic reasons.

  • Daredevils, who want to build a Python-3-only operating system environment, can change the contents of plpythonu's extension control and script files to make plpythonu be equivalent to plpython3u, keeping in mind that this would make their installation incompatible with most of the rest of the world.

See also the document What's New In Python 3.0 for more information about porting to Python 3.

It is not allowed to use PL/Python based on Python 2 and PL/Python based on Python 3 in the same session, because the symbols in the dynamic modules would clash, which could result in crashes of the PostgreSQL server process. There is a check that prevents mixing Python major versions in a session, which will abort the session if a mismatch is detected. It is possible, however, to use both PL/Python variants in the same database, from separate sessions.

FAQ