Що нового в Python 2.6

Автор:

A.M. Kuchling (amk в amk.ca)

У цій статті пояснюється нові функції в Python 2.6, випущеному 1 жовтня 2008 року. Графік випуску описано в PEP 361.

The major theme of Python 2.6 is preparing the migration path to Python 3.0, a major redesign of the language. Whenever possible, Python 2.6 incorporates new features and syntax from 3.0 while remaining compatible with existing code by not removing older features or syntax. When it’s not possible to do that, Python 2.6 tries to do what it can, adding compatibility functions in a future_builtins module and a -3 switch to warn about usages that will become unsupported in 3.0.

До стандартної бібліотеки додано кілька важливих нових пакетів, таких як модулі multiprocessing і json, але є не так багато нових функцій, які якимось чином не пов’язані з Python 3.0.

Python 2.6 також бачить ряд покращень і виправлень помилок у вихідному коді. Пошук у журналах змін виявив, що між Python 2.5 і 2.6 було застосовано 259 патчів і 612 виправлених помилок. Обидві цифри, ймовірно, занижені.

Ця стаття не намагається надати повну специфікацію нових функцій, натомість надає зручний огляд. Щоб отримати повну інформацію, зверніться до документації для Python 2.6. Якщо ви хочете зрозуміти обґрунтування дизайну та впровадження, зверніться до PEP для конкретної нової функції. Коли це можливо, «Що нового в Python» посилається на елемент помилки/виправлення для кожної зміни.

Python 3.0

Цикл розробки Python версій 2.6 і 3.0 був синхронізований, альфа- і бета-версії для обох версій були зроблені в ті самі дні. Розробка версії 3.0 вплинула на багато функцій версії 2.6.

Python 3.0 — це масштабна переробка Python, яка порушує сумісність із серією 2.x. Це означає, що існуючий код Python потребує певного перетворення, щоб працювати на Python 3.0. Однак не всі зміни в 3.0 обов’язково порушують сумісність. У випадках, коли нові функції не призведуть до поломки існуючого коду, їх було перенесено до версії 2.6 і описано у відповідному місці в цьому документі. Ось деякі з функцій версії 3.0:

  • A __complex__() method for converting objects to a complex number.

  • Альтернативний синтаксис для перехоплення винятків: except TypeError as exc.

  • The addition of functools.reduce() as a synonym for the built-in reduce() function.

Python 3.0 adds several new built-in functions and changes the semantics of some existing builtins. Functions that are new in 3.0 such as bin() have simply been added to Python 2.6, but existing builtins haven’t been changed; instead, the future_builtins module has versions with the new 3.0 semantics. Code written to be compatible with 3.0 can do from future_builtins import hex, map as necessary.

A new command-line switch, -3, enables warnings about features that will be removed in Python 3.0. You can run code with this switch to see how much work will be necessary to port code to 3.0. The value of this switch is available to Python code as the boolean variable sys.py3kwarning, and to C extension code as Py_Py3kWarningFlag.

Дивись також

The 3xxx series of PEPs, which contains proposals for Python 3.0. PEP 3000 describes the development process for Python 3.0. Start with PEP 3100 that describes the general goals for Python 3.0, and then explore the higher-numbered PEPs that propose specific features.

Зміни в процесі розробки

Поки розроблялася версія 2.6, процес розробки Python зазнав двох значних змін: ми перейшли від засобу відстеження проблем SourceForge до налаштованої інсталяції Roundup, а документацію було перетворено з LaTeX на reStructuredText.

Новий засіб відстеження проблем: огляд

Протягом тривалого часу розробники Python дедалі більше дратувалися програмою відстеження помилок SourceForge. Розміщене рішення SourceForge не дозволяє багато налаштовувати; наприклад, неможливо було налаштувати життєвий цикл проблем.

The infrastructure committee of the Python Software Foundation therefore posted a call for issue trackers, asking volunteers to set up different products and import some of the bugs and patches from SourceForge. Four different trackers were examined: Jira, Launchpad, Roundup, and Trac. The committee eventually settled on Jira and Roundup as the two candidates. Jira is a commercial product that offers no-cost hosted instances to free-software projects; Roundup is an open-source project that requires volunteers to administer it and a server to host it.

Після публікації заклику до волонтерів було встановлено нову установку Roundup на https://bugs.python.org. Одна інсталяція Roundup може розмістити кілька трекерів, і цей сервер тепер також розміщує трекери проблем для Jython і для веб-сайту Python. Він, безсумнівно, знайде інші застосування в майбутньому. Там, де це можливо, це видання «Що нового в Python» містить посилання на елемент помилки/виправлення для кожної зміни.

Hosting of the Python bug tracker is kindly provided by Upfront Systems of Stellenbosch, South Africa. Martin von Löwis put a lot of effort into importing existing bugs and patches from SourceForge; his scripts for this import operation are at https://svn.python.org/view/tracker/importer/ and may be useful to other projects wishing to move from SourceForge to Roundup.

Дивись також

https://bugs.python.org

Відстежувач помилок Python.

https://bugs.jython.org:

Відстежувач помилок Jython.

https://roundup.sourceforge.io/

Зведення завантажень і документації.

https://svn.python.org/view/tracker/importer/

Сценарії перетворення Мартіна фон Льовіса.

Новий формат документації: reStructuredText за допомогою Sphinx

Документація Python була написана з використанням LaTeX з моменту початку проекту приблизно в 1989 році. У 1980-х і на початку 1990-х більшість документації роздруковували для подальшого вивчення, а не переглядали в Інтернеті. LaTeX широко використовувався, тому що він забезпечував привабливий друкований результат, залишаючись простим для написання після вивчення основних правил розмітки.

Сьогодні LaTeX все ще використовується для написання публікацій, призначених для друку, але ландшафт інструментів програмування змінився. Ми більше не друкуємо купу документів; замість цього ми переглядаємо його в Інтернеті, і HTML став найважливішим форматом для підтримки. На жаль, перетворення LaTeX на HTML є досить складним, і Фред Л. Дрейк молодший, давній редактор документації Python, витратив багато часу на підтримку процесу перетворення. Час від часу люди пропонували конвертувати документацію в SGML, а пізніше в XML, але якісне перетворення є головним завданням, і ніхто ніколи не витрачав час, необхідний для завершення роботи.

During the 2.6 development cycle, Georg Brandl put a lot of effort into building a new toolchain for processing the documentation. The resulting package is called Sphinx, and is available from https://www.sphinx-doc.org/.

Sphinx зосереджується на виведенні HTML, виробляючи привабливий і сучасний HTML; друкований вихід все ще підтримується через перетворення на LaTeX. Формат введення – reStructuredText, синтаксис розмітки, який підтримує спеціальні розширення та директиви, який зазвичай використовується в спільноті Python.

Sphinx — це окремий пакет, який можна використовувати для написання, і майже два десятки інших проектів (зазначені на веб-сайті Sphinx) прийняли Sphinx як інструмент для документування.

Дивись також

Документування Python

Описує, як писати документацію для Python.

Sphinx

Документація та код для Sphinx toolchain.

Docutils

Базовий аналізатор reStructuredText і набір інструментів.

PEP 343: оператор «з».

Попередня версія, Python 2.5, додала інструкцію „with“ як необов’язкову функцію, яку можна було ввімкнути за допомогою директиви from __future__ import with_statement. У версії 2.6 цей оператор більше не потрібно спеціально вмикати; це означає, що with тепер завжди є ключовим словом. Решта цього розділу є копією відповідного розділу з документа «Що нового в Python 2.5»; якщо ви знайомі з оператором „with“ з Python 2.5, ви можете пропустити цей розділ.

Інструкція „with“ уточнює код, який раніше використовував блоки try...finally, щоб забезпечити виконання коду очищення. У цьому розділі я обговорю твердження, як воно буде зазвичай використовуватися. У наступному розділі я розгляну деталі реалізації та покажу, як писати об’єкти для використання з цим оператором.

Оператор „with“ — це структура потоку керування, основна структура якої:

with expression [as variable]:
    with-block

The expression is evaluated, and it should result in an object that supports the context management protocol (that is, has __enter__() and __exit__() methods).

The object’s __enter__() is called before with-block is executed and therefore can run set-up code. It also may return a value that is bound to the name variable, if given. (Note carefully that variable is not assigned the result of expression.)

After execution of the with-block is finished, the object’s __exit__() method is called, even if the block raised an exception, and can therefore run clean-up code.

Деякі стандартні об’єкти Python тепер підтримують протокол керування контекстом і можуть використовуватися з оператором „with“. Одним із прикладів є файлові об’єкти:

with open('/etc/passwd', 'r') as f:
    for line in f:
        print line
        ... more processing code ...

Після виконання цього оператора файловий об’єкт у f буде автоматично закрито, навіть якщо цикл for викликав виняток під час проходження блоку.

Примітка

In this case, f is the same object created by open(), because __enter__() returns self.

Блокування та змінні умови модуля threading також підтримують оператор „with“:

lock = threading.Lock()
with lock:
    # Critical section of code
    ...

Блокування встановлюється перед виконанням блоку та завжди знімається після завершення блоку.

The localcontext() function in the decimal module makes it easy to save and restore the current decimal context, which encapsulates the desired precision and rounding characteristics for computations:

from decimal import Decimal, Context, localcontext

# Displays with default precision of 28 digits
v = Decimal('578')
print v.sqrt()

with localcontext(Context(prec=16)):
    # All code in this block uses a precision of 16 digits.
    # The original context is restored on exiting the block.
    print v.sqrt()

Написання менеджерів контексту

Під капотом оператор „with“ досить складний. Більшість людей використовуватимуть „with“ тільки в компанії з існуючими об’єктами, і їм не потрібно знати ці деталі, тому ви можете пропустити решту цього розділу, якщо хочете. Авторам нових об’єктів потрібно буде зрозуміти деталі базової реалізації та продовжувати читати.

Загальне пояснення протоколу керування контекстом таке:

  • The expression is evaluated and should result in an object called a «context manager». The context manager must have __enter__() and __exit__() methods.

  • The context manager’s __enter__() method is called. The value returned is assigned to VAR. If no as VAR clause is present, the value is simply discarded.

  • Код у BLOCK виконується.

  • If BLOCK raises an exception, the context manager’s __exit__() method is called with three arguments, the exception details (type, value, traceback, the same values returned by sys.exc_info(), which can also be None if no exception occurred). The method’s return value controls whether an exception is re-raised: any false value re-raises the exception, and True will result in suppressing it. You’ll only rarely want to suppress the exception, because if you do the author of the code containing the „with“ statement will never realize anything went wrong.

  • If BLOCK didn’t raise an exception, the __exit__() method is still called, but type, value, and traceback are all None.

Давайте поміркуємо на прикладі. Я не буду представляти детальний код, а лише накидаю методи, необхідні для бази даних, яка підтримує транзакції.

(Для людей, які не знайомі з термінологією бази даних: набір змін до бази даних групується в транзакцію. Транзакції можуть бути або зафіксованими, тобто всі зміни записуються в базу даних, або відкоченими, тобто всі зміни скасовуються та база даних не змінена. Для отримання додаткової інформації зверніться до будь-якого підручника з баз даних.)

Припустімо, що є об’єкт, що представляє з’єднання з базою даних. Нашою метою буде дозволити користувачеві писати такий код:

db_connection = DatabaseConnection()
with db_connection as cursor:
    cursor.execute('insert into ...')
    cursor.execute('delete from ...')
    # ... more operations ...

The transaction should be committed if the code in the block runs flawlessly or rolled back if there’s an exception. Here’s the basic interface for DatabaseConnection that I’ll assume:

class DatabaseConnection:
    # Database interface
    def cursor(self):
        "Returns a cursor object and starts a new transaction"
    def commit(self):
        "Commits current transaction"
    def rollback(self):
        "Rolls back current transaction"

The __enter__() method is pretty easy, having only to start a new transaction. For this application the resulting cursor object would be a useful result, so the method will return it. The user can then add as cursor to their „with“ statement to bind the cursor to a variable name.

class DatabaseConnection:
    ...
    def __enter__(self):
        # Code to start a new transaction
        cursor = self.cursor()
        return cursor

The __exit__() method is the most complicated because it’s where most of the work has to be done. The method has to check if an exception occurred. If there was no exception, the transaction is committed. The transaction is rolled back if there was an exception.

У наведеному нижче коді виконання просто припиниться в кінці функції, повертаючи значення за замовчуванням None. None є хибним, тому виняток буде знову створено автоматично. Якщо ви бажаєте, ви можете бути більш чіткими та додати оператор return у позначене місце.

class DatabaseConnection:
    ...
    def __exit__(self, type, value, tb):
        if tb is None:
            # No exception, so commit
            self.commit()
        else:
            # Exception occurred, so rollback.
            self.rollback()
            # return False

Модуль contextlib

Модуль contextlib надає деякі функції та декоратор, корисні під час написання об’єктів для використання з оператором „with“.

The decorator is called @~contextlib.contextmanager, and lets you write a single generator function instead of defining a new class. The generator should yield exactly one value. The code up to the yield will be executed as the __enter__() method, and the value yielded will be the method’s return value that will get bound to the variable in the „with“ statement’s as clause, if any. The code after the yield will be executed in the __exit__() method. Any exception raised in the block will be raised by the yield statement.

Використовуючи цей декоратор, наш приклад бази даних із попереднього розділу можна записати так:

from contextlib import contextmanager

@contextmanager
def db_transaction(connection):
    cursor = connection.cursor()
    try:
        yield cursor
    except:
        connection.rollback()
        raise
    else:
        connection.commit()

db = DatabaseConnection()
with db_transaction(db) as cursor:
    ...

Модуль contextlib також має функцію nested(mgr1, mgr2, ...), яка поєднує кілька контекстних менеджерів, тому вам не потрібно писати вкладений „with“ заяви. У цьому прикладі один оператор „with“ запускає транзакцію бази даних і отримує блокування потоку:

lock = threading.Lock()
with nested (db_transaction(db), lock) as (cursor, locked):
    ...

Finally, the closing() function returns its argument so that it can be bound to a variable, and calls the argument’s .close() method at the end of the block.

import urllib, sys
from contextlib import closing

with closing(urllib.urlopen('http://www.yahoo.com')) as f:
    for line in f:
        sys.stdout.write(line)

Дивись також

PEP 343 - оператор «з».

PEP, написаний Гвідо ван Россумом і Ніком Когланом; реалізований Майком Блендом, Гвідо ван Россумом і Нілом Норвітцем. PEP показує код, згенерований для оператора „with“, який може бути корисним для вивчення того, як працює оператор.

Документація для модуля contextlib.

PEP 366: Явний відносний імпорт із основного модуля

Перемикач Python -m дозволяє запускати модуль як сценарій. Коли ви запускали модуль, який знаходився всередині пакета, відносний імпорт не працював належним чином.

The fix for Python 2.6 adds a module.__package__ attribute. When this attribute is present, relative imports will be relative to the value of this attribute instead of the __name__ attribute.

PEP 302-style importers can then set __package__ as necessary. The runpy module that implements the -m switch now does this, so relative imports will now work correctly in scripts running from inside a package.

PEP 370: каталог site-packages для кожного користувача

When you run Python, the module search path sys.path usually includes a directory whose path ends in "site-packages". This directory is intended to hold locally installed packages available to all users using a machine or a particular site installation.

Python 2.6 представляє конвенцію для каталогів сайтів, призначених для користувача. Каталог залежить від платформи:

  • Unix і Mac OS X: ~/.local/

  • Windows: %APPDATA%/Python

У цьому каталозі будуть підкаталоги для певної версії, наприклад lib/python2.6/site-packages в Unix/Mac OS і Python26/site-packages у Windows.

If you don’t like the default directory, it can be overridden by an environment variable. PYTHONUSERBASE sets the root directory used for all Python versions supporting this feature. On Windows, the directory for application-specific data can be changed by setting the APPDATA environment variable. You can also modify the site.py file for your Python installation.

Цю функцію можна повністю вимкнути, запустивши Python із параметром -s або встановивши змінну середовища PYTHONNOUSERSITE.

Дивись також

PEP 370 - каталог site-packages для кожного користувача

PEP написаний і реалізований Крістіаном Хеймсом.

PEP 371: Пакет multiprocessing

Новий пакет multiprocessing дозволяє програмам Python створювати нові процеси, які виконуватимуть обчислення та повертатимуть результат батьківському. Батьківський і дочірній процеси можуть спілкуватися за допомогою черг і каналів, синхронізувати свої операції за допомогою блокувань і семафорів, а також можуть обмінюватися простими масивами даних.

The multiprocessing module started out as an exact emulation of the threading module using processes instead of threads. That goal was discarded along the path to Python 2.6, but the general approach of the module is still similar. The fundamental class is the Process, which is passed a callable object and a collection of arguments. The start() method sets the callable running in a subprocess, after which you can call the is_alive() method to check whether the subprocess is still running and the join() method to wait for the process to exit.

Ось простий приклад, коли підпроцес обчислить факториал. Функція, яка виконує обчислення, написана дивним чином, тому вона займає значно більше часу, коли вхідний аргумент кратний 4.

import time
from multiprocessing import Process, Queue


def factorial(queue, N):
    "Compute a factorial."
    # If N is a multiple of 4, this function will take much longer.
    if (N % 4) == 0:
        time.sleep(.05 * N/4)

    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Put the result on the queue
    queue.put(fact)

if __name__ == '__main__':
    queue = Queue()

    N = 5

    p = Process(target=factorial, args=(queue, N))
    p.start()
    p.join()

    result = queue.get()
    print 'Factorial', N, '=', result

Queue використовується для передачі результату факториалу. Об’єкт Queue зберігається в глобальній змінній. Дочірній процес використовуватиме значення змінної, коли був створений дочірній процес; оскільки це Queue, батько і дитина можуть використовувати об’єкт для спілкування. (Якщо батько змінить значення глобальної змінної, це не вплине на значення дочірньої системи, і навпаки.)

Two other classes, Pool and Manager, provide higher-level interfaces. Pool will create a fixed number of worker processes, and requests can then be distributed to the workers by calling apply() or apply_async() to add a single request, and map() or map_async() to add a number of requests. The following code uses a Pool to spread requests across 5 worker processes and retrieve a list of results:

from multiprocessing import Pool

def factorial(N, dictionary):
    "Compute a factorial."
    ...
p = Pool(5)
result = p.map(factorial, range(1, 1000, 10))
for v in result:
    print v

Це дає такий вихід:

1
39916800
51090942171709440000
8222838654177922817725562880000000
33452526613163807108170062053440751665152000000000
...

The other high-level interface, the Manager class, creates a separate server process that can hold master copies of Python data structures. Other processes can then access and modify these data structures using proxy objects. The following example creates a shared dictionary by calling the dict() method; the worker processes then insert values into the dictionary. (Locking is not done for you automatically, which doesn’t matter in this example. Manager’s methods also include Lock(), RLock(), and Semaphore() to create shared locks.)

import time
from multiprocessing import Pool, Manager

def factorial(N, dictionary):
    "Compute a factorial."
    # Calculate the result
    fact = 1L
    for i in range(1, N+1):
        fact = fact * i

    # Store result in dictionary
    dictionary[N] = fact

if __name__ == '__main__':
    p = Pool(5)
    mgr = Manager()
    d = mgr.dict()         # Create shared dictionary

    # Run tasks using the pool
    for N in range(1, 1000, 10):
        p.apply_async(factorial, (N, d))

    # Mark pool as closed -- no more tasks can be added.
    p.close()

    # Wait for tasks to exit
    p.join()

    # Output results
    for k, v in sorted(d.items()):
        print k, v

Це дасть результат:

1 1
11 39916800
21 51090942171709440000
31 8222838654177922817725562880000000
41 33452526613163807108170062053440751665152000000000
51 15511187532873822802242430164693032110632597200169861120000...

Дивись також

Документація для модуля multiprocessing.

PEP 371 - Додано багатопроцесорний пакет

PEP, написаний Джессі Ноллером і Річардом Оудкерком; реалізовано Річардом Оудкерком і Джессі Ноллером.

PEP 3101: Розширене форматування рядків

In Python 3.0, the % operator is supplemented by a more powerful string formatting method, format(). Support for the str.format() method has been backported to Python 2.6.

In 2.6, both 8-bit and Unicode strings have a .format() method that treats the string as a template and takes the arguments to be formatted. The formatting template uses curly brackets ({, }) as special characters:

>>> # Substitute positional argument 0 into the string.
>>> "User ID: {0}".format("root")
'User ID: root'
>>> # Use the named keyword arguments
>>> "User ID: {uid}   Last seen: {last_login}".format(
...    uid="root",
...    last_login = "5 Mar 2008 07:20")
'User ID: root   Last seen: 5 Mar 2008 07:20'

Фігурні дужки можна екранувати, подвоюючи їх:

>>> "Empty dict: {{}}".format()
"Empty dict: {}"

Імена полів можуть бути цілими числами, що вказують на позиційні аргументи, такі як {0}, {1 тощо, або назви ключових аргументів. Ви також можете надати складені назви полів, які зчитують атрибути або мають доступ до ключів словника:

>>> import sys
>>> print 'Platform: {0.platform}\nPython version: {0.version}'.format(sys)
Platform: darwin
Python version: 2.6a1+ (trunk:61261M, Mar  5 2008, 20:29:41)
[GCC 4.0.1 (Apple Computer, Inc. build 5367)]'

>>> import mimetypes
>>> 'Content-type: {0[.mp4]}'.format(mimetypes.types_map)
'Content-type: video/mp4'

Зауважте, що використовуючи нотацію у стилі словника, наприклад [.mp4], вам не потрібно брати лапки навколо рядка; він шукатиме значення, використовуючи .mp4 як ключ. Рядки, що починаються з числа, будуть перетворені на ціле число. Ви не можете писати складніші вирази всередині рядка форматування.

Поки що ми показали, як вказати, яке поле підставляти в результуючий рядок. Використовуване точне форматування також можна контролювати, додавши двокрапку, за якою йде специфікатор формату. Наприклад:

>>> # Field 0: left justify, pad to 15 characters
>>> # Field 1: right justify, pad to 6 characters
>>> fmt = '{0:15} ${1:>6}'
>>> fmt.format('Registration', 35)
'Registration    $    35'
>>> fmt.format('Tutorial', 50)
'Tutorial        $    50'
>>> fmt.format('Banquet', 125)
'Banquet         $   125'

Специфікатори формату можуть посилатися на інші поля через вкладення:

>>> fmt = '{0:{1}}'
>>> width = 15
>>> fmt.format('Invoice #1234', width)
'Invoice #1234  '
>>> width = 35
>>> fmt.format('Invoice #1234', width)
'Invoice #1234                      '

Можна вказати вирівнювання поля в межах бажаної ширини:

характер

Ефект

< (за умовчанням)

Вирівнювання по лівому краю

>

Вирівнювання по правому краю

^

центр

=

(Лише для числових типів) Додайте після знака.

Специфікатори формату також можуть містити тип представлення, який керує форматуванням значення. Наприклад, числа з плаваючою комою можна відформатувати як загальне число або в експоненціальній системі:

>>> '{0:g}'.format(3.75)
'3.75'
>>> '{0:e}'.format(3.75)
'3.750000e+00'

Доступні різноманітні типи презентацій. Зверніться до документації 2.6, щоб отримати повний список; ось зразок:

b

Двійковий. Виводить число за основою 2.

c

характер. Перетворює ціле число на відповідний символ Unicode перед друком.

d

Десяткове ціле число. Виводить число за основою 10.

о

Вісімковий формат. Виводить число за основою 8.

x

Шістнадцятковий формат. Виводить число за основою 16, використовуючи малі літери для цифр над 9.

e

Запис степеня. Друкує число в науковому записі, використовуючи літеру «e» для позначення степеня.

g

Загальний формат. Це друкує число як число з фіксованою комою, за винятком випадків, коли число надто велике, і в цьому випадку воно перемикається на позначення ступеня «e».

n

Номер. Це те саме, що «g» (для чисел з плаваючою точкою) або «d» (для цілих чисел), за винятком того, що для вставки відповідних символів-роздільників використовуються поточні параметри мови.

%

Відсоток. Множить число на 100 і відображається у фіксованому форматі („f“) із знаком відсотка.

Classes and types can define a __format__() method to control how they’re formatted. It receives a single argument, the format specifier:

def __format__(self, format_spec):
    if isinstance(format_spec, unicode):
        return unicode(str(self))
    else:
        return str(self)

There’s also a format() builtin that will format a single value. It calls the type’s __format__() method with the provided specifier:

>>> format(75.6564, '.2f')
'75.66'

Дивись також

Format string syntax

Довідкова документація для полів формату.

PEP 3101 - Розширене форматування рядків

PEP, написаний Таліним. Реалізовано Еріком Смітом.

PEP 3105: друк як функція

Оператор print стає функцією print() у Python 3.0. Зробивши print() функцією, можна замінити функцію, виконавши def print(...) або імпортувавши нову функцію з іншого місця.

У Python 2.6 є імпорт __future__, який видаляє print як синтаксис мови, дозволяючи замість цього використовувати функціональну форму. Наприклад:

>>> from __future__ import print_function
>>> print('# of entries', len(dictionary), file=sys.stderr)

Сигнатура нової функції:

def print(*args, sep=' ', end='\n', file=None)

Параметри такі:

  • args: позиційні аргументи, значення яких буде роздруковано.

  • sep: роздільник, який буде надруковано між аргументами.

  • end: кінцевий текст, який буде надруковано після виведення всіх аргументів.

  • file: файловий об’єкт, до якого буде надіслано вивід.

Дивись також

PEP 3105 - Зробити друк функцією

PEP, написаний Георгом Брандлом.

PEP 3110: Зміни обробки винятків

Однією з помилок, яку іноді роблять програмісти Python, є написання наступного коду:

try:
    ...
except TypeError, ValueError:  # Wrong!
    ...

Автор, ймовірно, намагається перехопити винятки TypeError і ValueError, але цей код насправді робить щось інше: він перехопить TypeError і прив’яже отриманий об’єкт винятку до локальної назви "ValueError". Виняток ValueError не буде перехоплено взагалі. Правильний код визначає кортеж винятків:

try:
    ...
except (TypeError, ValueError):
    ...

Ця помилка виникає через те, що використання коми тут неоднозначне: чи вказує вона на два різні вузли в дереві розбору, чи на один вузол, який є кортежем?

Python 3.0 робить це однозначним, замінюючи кому словом «як». Щоб перехопити виняток і зберегти об’єкт винятку в змінній exc, ви повинні написати:

try:
    ...
except TypeError as exc:
    ...

Python 3.0 підтримуватиме лише використання «as», і тому інтерпретує перший приклад як перехоплення двох різних винятків. Python 2.6 підтримує як кому, так і «as», тому наявний код працюватиме й надалі. Тому ми пропонуємо використовувати «as» під час написання нового коду Python, який виконуватиметься лише з 2.6.

Дивись також

PEP 3110 - Перехоплення винятків у Python 3000

PEP написав і реалізував Колін Вінтер.

PEP 3112: Байтові літерали

Python 3.0 використовує Unicode як основний рядковий тип мови та позначає 8-бітні літерали по-різному, або як b'string', або за допомогою конструктора bytes. Для майбутньої сумісності Python 2.6 додає bytes як синонім для типу str, а також підтримує нотацію b''.

Тип str 2.6 відрізняється від типу bytes 3.0 різними способами; головне, що конструктор зовсім інший. У 3.0 bytes([65, 66, 67]) складається з 3 елементів, які містять байти, що представляють ABC; у версії 2.6 bytes([65, 66, 67]) повертає 12-байтовий рядок, який представляє str() списку.

Основним використанням bytes у 2.6 буде написання тестів типу об’єкта, наприклад isinstance(x, bytes). Це допоможе конвертеру 2to3, який не може визначити, чи код 2.x передбачає, що рядки містять символи чи 8-бітні байти; Тепер ви можете використовувати або bytes, або str, щоб точно представити свій намір, і отриманий код також буде правильним у Python 3.0.

Існує також імпорт __future__, завдяки якому всі рядкові літерали стають рядками Unicode. Це означає, що керуючі послідовності \u можна використовувати для включення символів Unicode:

from __future__ import unicode_literals

s = ('\u751f\u3080\u304e\u3000\u751f\u3054'
     '\u3081\u3000\u751f\u305f\u307e\u3054')

print len(s)               # 12 Unicode characters

At the C level, Python 3.0 will rename the existing 8-bit string type, called PyStringObject in Python 2.x, to PyBytesObject. Python 2.6 uses #define to support using the names PyBytesObject(), PyBytes_Check(), PyBytes_FromStringAndSize(), and all the other functions and macros used with strings.

Екземпляри типу bytes незмінні, як і рядки. Новий тип bytearray зберігає змінну послідовність байтів:

>>> bytearray([65, 66, 67])
bytearray(b'ABC')
>>> b = bytearray(u'\u21ef\u3244', 'utf-8')
>>> b
bytearray(b'\xe2\x87\xaf\xe3\x89\x84')
>>> b[0] = '\xe3'
>>> b
bytearray(b'\xe3\x87\xaf\xe3\x89\x84')
>>> unicode(str(b), 'utf-8')
u'\u31ef \u3244'

Byte arrays support most of the methods of string types, such as startswith()/endswith(), find()/rfind(), and some of the methods of lists, such as append(), pop(), and reverse().

>>> b = bytearray('ABC')
>>> b.append('d')
>>> b.append(ord('e'))
>>> b
bytearray(b'ABCde')

Існує також відповідний C API з PyByteArray_FromObject(), PyByteArray_FromStringAndSize() та різними іншими функціями.

Дивись також

PEP 3112 - Байтові літерали в Python 3000

PEP, написаний Джейсоном Орендорфом; перенесено до 2.6 Крістіаном Хеймсом.

PEP 3116: Нова бібліотека введення-виведення

Python’s built-in file objects support a number of methods, but file-like objects don’t necessarily support all of them. Objects that imitate files usually support read() and write(), but they may not support readline(), for example. Python 3.0 introduces a layered I/O library in the io module that separates buffering and text-handling features from the fundamental read and write operations.

Модуль io пропонує три рівні абстрактних базових класів:

  • RawIOBase defines raw I/O operations: read(), readinto(), write(), seek(), tell(), truncate(), and close(). Most of the methods of this class will often map to a single system call. There are also readable(), writable(), and seekable() methods for determining what operations a given object will allow.

    У Python 3.0 є конкретні реалізації цього класу для файлів і сокетів, але Python 2.6 не реструктурував свої об’єкти файлів і сокетів таким чином.

  • BufferedIOBase is an abstract base class that buffers data in memory to reduce the number of system calls used, making I/O processing more efficient. It supports all of the methods of RawIOBase, and adds a raw attribute holding the underlying raw object.

    There are five concrete classes implementing this ABC. BufferedWriter and BufferedReader are for objects that support write-only or read-only usage that have a seek() method for random access. BufferedRandom objects support read and write access upon the same underlying stream, and BufferedRWPair is for objects such as TTYs that have both read and write operations acting upon unconnected streams of data. The BytesIO class supports reading, writing, and seeking over an in-memory buffer.

  • TextIOBase: Provides functions for reading and writing strings (remember, strings will be Unicode in Python 3.0), and supporting universal newlines. TextIOBase defines the readline() method and supports iteration upon objects.

    There are two concrete implementations. TextIOWrapper wraps a buffered I/O object, supporting all of the methods for text I/O and adding a buffer attribute for access to the underlying object. StringIO simply buffers everything in memory without ever writing anything to disk.

    (In Python 2.6, io.StringIO is implemented in pure Python, so it’s pretty slow. You should therefore stick with the existing StringIO module or cStringIO for now. At some point Python 3.0’s io module will be rewritten into C for speed, and perhaps the C implementation will be backported to the 2.x releases.)

У Python 2.6 базові реалізації не були реструктуризовані для створення поверх класів модуля io. Модуль надається, щоб спростити написання коду, сумісного з версією 3.0, і позбавити розробників від зусиль написання власних реалізацій буферизації та текстового введення-виведення.

Дивись також

PEP 3116 - Новий I/O

PEP, написаний Даніелем Штуцбахом, Майком Вердоне та Гвідо ван Россумом. Код Гвідо ван Россума, Георга Брандла, Уолтера Доервальда, Джеремі Гілтона, Мартіна фон Льовіса, Тоні Лоундса та інших.

PEP 3118: Переглянутий буферний протокол

Буферний протокол — це API рівня C, який дозволяє типам Python обмінюватися покажчиками на свої внутрішні представлення. Файл із відображенням пам’яті можна розглядати, наприклад, як буфер символів, і це дозволяє іншому модулю, такому як re розглядати файли, відображені в пам’яті, як рядок символів для пошуку.

Основними користувачами протоколу буфера є пакети числової обробки, такі як NumPy, які відкривають внутрішнє представлення масивів, щоб абоненти могли записувати дані безпосередньо в масив замість використання повільнішого API. Цей PEP оновлює протокол буфера в світлі досвіду розробки NumPy, додаючи ряд нових функцій, таких як вказівка форми масиву або блокування області пам’яті.

Найважливішою новою функцією C API є PyObject_GetBuffer(PyObject *obj, Py_buffer *view, int flags), яка приймає об’єкт і набір прапорів і заповнює структуру Py_buffer інформацією про представлення пам’яті об’єкта. Об’єкти можуть використовувати цю операцію для блокування пам’яті на місці, поки зовнішній виклик може модифікувати вміст, тому існує відповідний PyBuffer_Release(Py_buffer *view), щоб вказати, що зовнішній виклик завершив роботу.

Аргумент flags для PyObject_GetBuffer() визначає обмеження щодо пам’яті, що повертається. Деякі приклади:

  • PyBUF_WRITABLE indicates that the memory must be writable.

  • PyBUF_LOCK requests a read-only or exclusive lock on the memory.

  • PyBUF_C_CONTIGUOUS and PyBUF_F_CONTIGUOUS requests a C-contiguous (last dimension varies the fastest) or Fortran-contiguous (first dimension varies the fastest) array layout.

Два нові коди аргументів для PyArg_ParseTuple(), s* і z* повертають заблоковані об’єкти буфера для параметра.

Дивись також

PEP 3118 - Перегляд буферного протоколу

PEP, написаний Тревісом Оліфантом і Карлом Бенксом; реалізований Тревісом Оліфантом.

PEP 3119: Абстрактні базові класи

Some object-oriented languages such as Java support interfaces, declaring that a class has a given set of methods or supports a given access protocol. Abstract Base Classes (or ABCs) are an equivalent feature for Python. The ABC support consists of an abc module containing a metaclass called ABCMeta, special handling of this metaclass by the isinstance() and issubclass() builtins, and a collection of basic ABCs that the Python developers think will be widely useful. Future versions of Python will probably add more ABCs.

Let’s say you have a particular class and wish to know whether it supports dictionary-style access. The phrase «dictionary-style» is vague, however. It probably means that accessing items with obj[1] works. Does it imply that setting items with obj[2] = value works? Or that the object will have keys(), values(), and items() methods? What about the iterative variants such as iterkeys()? copy`and :meth:()!update`? Iterating over the object with iter()?

The Python 2.6 collections module includes a number of different ABCs that represent these distinctions. Iterable indicates that a class defines __iter__(), and Container means the class defines a __contains__() method and therefore supports x in y expressions. The basic dictionary interface of getting items, setting items, and keys(), values(), and items(), is defined by the MutableMapping ABC.

Ви можете вивести власні класи з конкретного ABC, щоб вказати, що вони підтримують цей інтерфейс ABC:

import collections

class Storage(collections.MutableMapping):
    ...

Alternatively, you could write the class without deriving from the desired ABC and instead register the class by calling the ABC’s register() method:

import collections

class Storage:
    ...

collections.MutableMapping.register(Storage)

For classes that you write, deriving from the ABC is probably clearer. The register() method is useful when you’ve written a new ABC that can describe an existing type or class, or if you want to declare that some third-party class implements an ABC. For example, if you defined a PrintableType ABC, it’s legal to do:

# Register Python's types
PrintableType.register(int)
PrintableType.register(float)
PrintableType.register(str)

Класи повинні підкорятися семантиці, визначеній ABC, але Python не може перевірити це; автор класу повинен зрозуміти вимоги ABC і відповідним чином реалізувати код.

Щоб перевірити, чи підтримує об’єкт певний інтерфейс, тепер можна написати:

def func(d):
    if not isinstance(d, collections.MutableMapping):
        raise ValueError("Mapping object expected, not %r" % d)

Не думайте, що вам потрібно починати виписувати багато чеків, як у наведеному вище прикладі. Python має сильну традицію качиного введення, коли явна перевірка типу ніколи не виконується, а код просто викликає методи об’єкта, вірячи, що ці методи будуть присутні, і створює виняток, якщо їх немає. Будьте розсудливими, перевіряючи наявність азбуки, і робіть це лише там, де це абсолютно необхідно.

Ви можете написати власні азбуки, використовуючи abc.ABCMeta як метаклас у визначенні класу:

from abc import ABCMeta, abstractmethod

class Drawable():
    __metaclass__ = ABCMeta

    @abstractmethod
    def draw(self, x, y, scale=1.0):
        pass

    def draw_doubled(self, x, y):
        self.draw(x, y, scale=2.0)


class Square(Drawable):
    def draw(self, x, y, scale):
        ...

In the Drawable ABC above, the draw_doubled() method renders the object at twice its size and can be implemented in terms of other methods described in Drawable. Classes implementing this ABC therefore don’t need to provide their own implementation of draw_doubled(), though they can do so. An implementation of draw() is necessary, though; the ABC can’t provide a useful generic implementation.

You can apply the @~abc.abstractmethod decorator to methods such as draw() that must be implemented; Python will then raise an exception for classes that don’t define the method. Note that the exception is only raised when you actually try to create an instance of a subclass lacking the method:

>>> class Circle(Drawable):
...     pass
...
>>> c = Circle()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: Can't instantiate abstract class Circle with abstract methods draw
>>>

Атрибути абстрактних даних можна оголосити за допомогою декоратора @abstractproperty:

from abc import abstractproperty
...

@abstractproperty
def readonly(self):
   return self._x

Subclasses must then define a readonly property.

Дивись також

PEP 3119 - Представляємо абстрактні базові класи

PEP, написаний Гвідо ван Россумом і Таліном. Реалізовано Гвідо ван Россумом. Перенесено до 2.6 Бенджаміном Арангуреном разом з Алексом Мартеллі.

PEP 3127: Підтримка цілочисельного літералу та синтаксис

Python 3.0 змінює синтаксис для вісімкових (за основою 8) цілих літералів, додаючи до них префікс «0o» або «0O» замість початкового нуля, і додає підтримку двійкових (за основою 2) цілих літералів, що позначаються «0b» або префікс «0B».

Python 2.6 не припиняє підтримку початкового 0, що сигналізує про вісімкове число, але додає підтримку «0o» і «0b»:

>>> 0o21, 2*8 + 1
(17, 17)
>>> 0b101111
47

Вбудована функція oct() все ще повертає числа з префіксом нуля на початку, а нова вбудована функція bin() повертає двійкове представлення числа:

>>> oct(42)
'052'
>>> future_builtins.oct(42)
'0o52'
>>> bin(173)
'0b10101101'

The int() and long() builtins will now accept the «0o» and «0b» prefixes when base-8 or base-2 are requested, or when the base argument is zero (signalling that the base used should be determined from the string):

>>> int ('0o52', 0)
42
>>> int('1101', 2)
13
>>> int('0b1101', 2)
13
>>> int('0b1101', 0)
13

Дивись також

PEP 3127 - Підтримка цілочисельного літералу та синтаксис

PEP, написаний Патріком Мопіном; повернуто до 2.6 Еріком Смітом.

PEP 3129: Декоратори класу

Декоратори були розширені з функцій до класів. Тепер можна писати:

@foo
@bar
class A:
  pass

Це еквівалентно:

class A:
  pass

A = foo(bar(A))

Дивись також

PEP 3129 - Декоратори класу

PEP, автор Колін Вінтер.

PEP 3141: Ієрархія типів чисел

Python 3.0 додає кілька абстрактних базових класів для числових типів, натхненних числовою вежею Scheme. Ці класи було перенесено до версії 2.6 як модуль numbers.

The most general ABC is Number. It defines no operations at all, and only exists to allow checking if an object is a number by doing isinstance(obj, Number).

Complex is a subclass of Number. Complex numbers can undergo the basic operations of addition, subtraction, multiplication, division, and exponentiation, and you can retrieve the real and imaginary parts and obtain a number’s conjugate. Python’s built-in complex type is an implementation of Complex.

Real further derives from Complex, and adds operations that only work on real numbers: floor(), trunc(), rounding, taking the remainder mod N, floor division, and comparisons.

Rational numbers derive from Real, have numerator and denominator properties, and can be converted to floats. Python 2.6 adds a simple rational-number class, Fraction, in the fractions module. (It’s called Fraction instead of Rational to avoid a name clash with numbers.Rational.)

Integral numbers derive from Rational, and can be shifted left and right with << and >>, combined using bitwise operations such as & and |, and can be used as array indexes and slice boundaries.

In Python 3.0, the PEP slightly redefines the existing builtins round(), math.floor(), math.ceil(), and adds a new one, math.trunc(), that’s been backported to Python 2.6. math.trunc() rounds toward zero, returning the closest Integral that’s between the function’s argument and zero.

Дивись також

PEP 3141 - Ієрархія типів для чисел

PEP, написаний Джеффрі Яскіним.

Числова вежа схеми, з посібника Guile.

Scheme’s number datatypes from the R5RS Scheme specification.

Модуль fractions

Щоб заповнити ієрархію числових типів, модуль fractions надає клас раціональних чисел. Раціональні числа зберігають свої значення як чисельник і знаменник, утворюючи дріб, і можуть точно представляти числа, такі як 2/3, які числа з плаваючою комою можуть лише приблизно оцінити.

The Fraction constructor takes two Integral values that will be the numerator and denominator of the resulting fraction.

>>> from fractions import Fraction
>>> a = Fraction(2, 3)
>>> b = Fraction(2, 5)
>>> float(a), float(b)
(0.66666666666666663, 0.40000000000000002)
>>> a+b
Fraction(16, 15)
>>> a/b
Fraction(5, 3)

For converting floating-point numbers to rationals, the float type now has an as_integer_ratio() method that returns the numerator and denominator for a fraction that evaluates to the same floating-point value:

>>> (2.5) .as_integer_ratio()
(5, 2)
>>> (3.1415) .as_integer_ratio()
(7074029114692207L, 2251799813685248L)
>>> (1./3) .as_integer_ratio()
(6004799503160661L, 18014398509481984L)

Зауважте, що значення, які можна апроксимувати лише числами з плаваючою комою, наприклад 1./3, не спрощуються до числа, яке апроксимується; дріб намагається точно збігатися зі значенням з плаваючою комою.

Модуль fractions базується на реалізації Sjoerd Mullender, яка довгий час була в каталозі Demo/classes/ Python. Ця реалізація була значно оновлена Джеффрі Яскіним.

Інші зміни мови

Деякі менші зміни, внесені до основної мови Python:

  • Каталоги та zip-архіви, що містять файл __main__.py, тепер можна виконувати безпосередньо, передавши їх імена інтерпретатору. Каталог або zip-архів автоматично вставляється як перший запис у sys.path. (Пропозиція та початковий патч Енді Чу, згодом переглянуті Філіпом Дж. Ебі та Ніком Когланом; bpo-1739468.)

  • The hasattr() function was catching and ignoring all errors, under the assumption that they meant a __getattr__() method was failing somehow and the return value of hasattr() would therefore be False. This logic shouldn’t be applied to KeyboardInterrupt and SystemExit, however; Python 2.6 will no longer discard such exceptions when hasattr() encounters them. (Fixed by Benjamin Peterson; bpo-2196.)

  • Під час виклику функції за допомогою синтаксису ** для надання ключових аргументів вам більше не потрібно використовувати словник Python; будь-яке відображення тепер працюватиме:

    >>> def f(**kw):
    ...    print sorted(kw)
    ...
    >>> ud=UserDict.UserDict()
    >>> ud['a'] = 1
    >>> ud['b'] = 'string'
    >>> f(**ud)
    ['a', 'b']
    

    (Надав Олександр Бєлопольський; bpo-1686487.)

    Також стало законним надавати аргументи ключового слова після аргументу *args для виклику функції.

    >>> def f(*args, **kw):
    ...     print args, kw
    ...
    >>> f(1,2,3, *(4,5,6), keyword=13)
    (1, 2, 3, 4, 5, 6) {'keyword': 13}
    

    Раніше це була синтаксична помилка. (Надав Аморі Форже д’Арк; bpo-3473.)

  • Нова вбудована функція next(iterator, [default]) повертає наступний елемент із зазначеного ітератора. Якщо вказано аргумент default, він буде повернений, якщо iterator вичерпано; інакше буде викликано виняток StopIteration. (Бекпортовано в bpo-2719.)

  • Tuples now have index() and count() methods matching the list type’s index() and count() methods:

    >>> t = (0,1,2,3,4,0,1,2)
    >>> t.index(3)
    3
    >>> t.count(0)
    2
    

    (Надав Реймонд Геттінгер)

  • Вбудовані типи тепер мають покращену підтримку розширеного синтаксису нарізки, приймаючи різні комбінації (початок, зупинка, крок). Раніше підтримка була частковою, і певні кутові випадки не працювали. (Реалізовано Томасом Воутерсом.)

  • Properties now have three decorators, @~property.getter, @~property.setter and @~property.deleter, that are decorators providing useful shortcuts for adding a getter, setter or deleter function to an existing property. You would use them like this:

    class C(object):
        @property
        def x(self):
            return self._x
    
        @x.setter
        def x(self, value):
            self._x = value
    
        @x.deleter
        def x(self):
            del self._x
    
    class D(C):
        @C.x.getter
        def x(self):
            return self._x * 2
    
        @x.setter
        def x(self, value):
            self._x = value / 2
    
  • Several methods of the built-in set types now accept multiple iterables: intersection(), intersection_update(), union(), update(), difference() and difference_update().

    >>> s=set('1234567890')
    >>> s.intersection('abc123', 'cdf246')  # Intersection between all inputs
    set(['2'])
    >>> s.difference('246', '789')
    set(['1', '0', '3', '5'])
    

    (Надав Реймонд Геттінгер.)

  • Було додано багато функцій з плаваючою комою. Функція float() тепер перетворить рядок nan на значення IEEE 754 Not A Number, а +inf і -inf на позитивну або негативну нескінченність. Це працює на будь-якій платформі із семантикою IEEE 754. (Надав Крістіан Хаймес; bpo-1635.)

    Other functions in the math module, isinf() and isnan(), return true if their floating-point argument is infinite or Not A Number. (bpo-1640)

    Було додано функції перетворення для перетворення чисел з плаваючою комою в шістнадцяткові рядки (bpo-3008). Ці функції перетворюють числа з плаваючою точкою в рядкове представлення та з нього, не вводячи помилок округлення через перетворення між десятковим і двійковим. Поплавки мають метод hex(), який повертає представлення рядка, а метод float.fromhex() перетворює рядок назад у число:

    >>> a = 3.75
    >>> a.hex()
    '0x1.e000000000000p+1'
    >>> float.fromhex('0x1.e000000000000p+1')
    3.75
    >>> b=1./3
    >>> b.hex()
    '0x1.5555555555555p-2'
    
  • Числова тонкість: під час створення комплексного числа з двох чисел з плаваючою точкою в системах, які підтримують нулі зі знаком (-0 і +0), конструктор complex() тепер збереже знак нуля. (Виправлено Марком Т. Дікінсоном; bpo-1507.)

  • Classes that inherit a __hash__() method from a parent class can set __hash__ = None to indicate that the class isn’t hashable. This will make hash(obj) raise a TypeError and the class will not be indicated as implementing the Hashable ABC.

    You should do this when you’ve defined a __cmp__() or __eq__() method that compares objects by their value rather than by identity. All objects have a default hash method that uses id(obj) as the hash value. There’s no tidy way to remove the __hash__() method inherited from a parent class, so assigning None was implemented as an override. At the C level, extensions can set tp_hash to PyObject_HashNotImplemented(). (Fixed by Nick Coghlan and Amaury Forgeot d’Arc; bpo-2235.)

  • Виняток GeneratorExit тепер є підкласами BaseException замість Exception. Це означає, що обробник винятків, який виконує except Exception:, не буде випадково перехоплювати GeneratorExit. (Надав Чед Остін; bpo-1537.)

  • Generator objects now have a gi_code attribute that refers to the original code object backing the generator. (Contributed by Collin Winter; bpo-1473257.)

  • Вбудована функція compile() тепер приймає аргументи ключових слів, а також позиційні параметри. (Надав Томас Воутерс; bpo-1444529.)

  • Конструктор complex() тепер приймає рядки, що містять комплексні числа в круглих дужках, що означає, що complex(repr(cplx)) тепер передаватиме значення. Наприклад, complex('(3+4j)') тепер повертає значення (3+4j). (bpo-1491866)

  • The string translate() method now accepts None as the translation table parameter, which is treated as the identity transformation. This makes it easier to carry out operations that only delete characters. (Contributed by Bengt Richter and implemented by Raymond Hettinger; bpo-1193128.)

  • The built-in dir() function now checks for a __dir__() method on the objects it receives. This method must return a list of strings containing the names of valid attributes for the object, and lets the object control the value that dir() produces. Objects that have __getattr__() or __getattribute__() methods can use this to advertise pseudo-attributes they will honor. (bpo-1591665)

  • Instance method objects have new attributes for the object and function comprising the method; the new synonym for im_self is __self__, and im_func is also available as __func__. The old names are still supported in Python 2.6, but are gone in 3.0.

  • Незрозуміла зміна: коли ви використовуєте функцію locals() всередині оператора class, отриманий словник більше не повертає вільні змінні. (У цьому випадку вільні змінні — це змінні, на які посилається оператор class, які не є атрибутами класу.)

Оптимізації

  • Модуль warnings було переписано мовою C. Це дає змогу викликати попередження від аналізатора, а також може пришвидшити запуск інтерпретатора. (Надано Нілом Норвітцем і Бреттом Кенноном; bpo-1631171.)

  • Об’єкти типу тепер мають кеш методів, що може зменшити роботу, необхідну для пошуку правильної реалізації методу для певного класу; після кешування інтерпретатору не потрібно проходити базові класи, щоб визначити правильний метод для виклику. Кеш очищається, якщо базовий клас або сам клас змінено, тому кеш має залишатися правильним навіть з огляду на динамічну природу Python. (Оригінальна оптимізація реалізована Арміном Ріго, оновлена для Python 2.6 Кевіном Джейкобсом; bpo-1700288.)

    За замовчуванням ця зміна застосовується лише до типів, які входять до складу ядра Python. Модулі розширення можуть не обов’язково бути сумісними з цим кешем, тому вони повинні явно додати Py_TPFLAGS_HAVE_VERSION_TAG до поля tp_flags модуля, щоб увімкнути кеш методів. (Щоб бути сумісним із кешем методів, код модуля розширення не повинен напряму отримувати доступ до члена tp_dict будь-якого з типів, які він реалізує, і змінювати його. Більшість модулів цього не роблять, але інтерпретатор Python не може визначте це. Перегляньте bpo-1878 для деякого обговорення.)

  • Виклики функцій, які використовують ключові аргументи, значно пришвидшуються завдяки швидкому порівнянню вказівників, що зазвичай економить час на повне порівняння рядків. (Надано Реймондом Геттінгером, після початкової реалізації Антуаном Пітру; bpo-1819.)

  • Усі функції в модулі struct були переписані мовою C завдяки роботі над спринтом Need For Speed. (Надав Реймонд Геттінгер.)

  • Деякі зі стандартних вбудованих типів тепер встановлюють біт у своїх об’єктах типу. Це прискорює перевірку того, чи є об’єкт підкласом одного з цих типів. (Надав Ніл Норвіц.)

  • Unicode strings now use faster code for detecting whitespace and line breaks; this speeds up the split() method by about 25% and splitlines() by 35%. (Contributed by Antoine Pitrou.) Memory usage is reduced by using pymalloc for the Unicode string’s data.

  • The with statement now stores the __exit__() method on the stack, producing a small speedup. (Implemented by Jeffrey Yasskin.)

  • Щоб зменшити використання пам’яті, збирач сміття тепер очищатиме внутрішні вільні списки під час збирання сміття найвищого покоління об’єктів. Це може швидше повернути пам’ять операційній системі.

Зміни перекладача

Two command-line options have been reserved for use by other Python implementations. The -J switch has been reserved for use by Jython for Jython-specific options, such as switches that are passed to the underlying JVM. -X has been reserved for options specific to a particular implementation of Python such as CPython, Jython, or IronPython. If either option is used with Python 2.6, the interpreter will report that the option isn’t currently used.

Тепер Python можна заборонити записувати файли .pyc або .pyo, вказавши перемикач -B інтерпретатору Python або налаштувавши середовище PYTHONDONTWRITEBYTECODE перед запуском інтерпретатора. Цей параметр доступний для програм Python як змінна sys.dont_write_bytecode, і код Python може змінити значення, щоб змінити поведінку інтерпретатора. (Надано Нілом Норвітцем і Георгом Брандлом.)

Кодування, що використовується для стандартного введення, виведення та стандартної помилки, можна вказати, встановивши змінну середовища PYTHONIOENCODING перед запуском інтерпретатора. Значення має бути рядком у формі <encoding> або <encoding> : <errorhandler>. Частина encoding визначає назву кодування, напр. utf-8 або latin-1; необов’язкова частина errorhandler визначає, що робити з символами, які не можуть бути оброблені кодуванням, і має бути одним із «помилка», «ігнорувати» або «замінити». (Надав Мартін фон Льовіс.)

Нові та вдосконалені модулі

Як і в кожному випуску, стандартна бібліотека Python отримала низку вдосконалень і виправлень помилок. Ось неповний список найбільш помітних змін, відсортованих за алфавітом назв модулів. Зверніться до файлу Misc/NEWS у дереві вихідних кодів, щоб отримати більш повний список змін, або перегляньте журнали Subversion, щоб отримати всі деталі.

  • The asyncore and asynchat modules are being actively maintained again, and a number of patches and bugfixes were applied. (Maintained by Josiah Carlson; see bpo-1736190 for one patch.)

  • The bsddb module also has a new maintainer, Jesús Cea Avión, and the package is now available as a standalone package. The web page for the package is www.jcea.es/programacion/pybsddb.htm. The plan is to remove the package from the standard library in Python 3.0, because its pace of releases is much more frequent than Python’s.

    The bsddb.dbshelve module now uses the highest pickling protocol available, instead of restricting itself to protocol 1. (Contributed by W. Barnes.)

  • The cgi module will now read variables from the query string of an HTTP POST request. This makes it possible to use form actions with URLs that include query strings such as «/cgi-bin/add.py?category=1». (Contributed by Alexandre Fiori and Nubis; bpo-1817.)

    The parse_qs() and parse_qsl() functions have been relocated from the cgi module to the urlparse module. The versions still available in the cgi module will trigger PendingDeprecationWarning messages in 2.6 (bpo-600362).

  • Модуль cmath зазнав значної редакції, внесеної Марком Дікінсоном і Крістіаном Хеймсом. Додано п’ять нових функцій:

    • polar() converts a complex number to polar form, returning the modulus and argument of the complex number.

    • rect() does the opposite, turning a modulus, argument pair back into the corresponding complex number.

    • phase() returns the argument (also called the angle) of a complex number.

    • isnan() returns True if either the real or imaginary part of its argument is a NaN.

    • isinf() returns True if either the real or imaginary part of its argument is infinite.

    The revisions also improved the numerical soundness of the cmath module. For all functions, the real and imaginary parts of the results are accurate to within a few units of least precision (ulps) whenever possible. See bpo-1381 for the details. The branch cuts for asinh(), atanh(), and atan() have also been corrected.

    Значно розширено тести для модуля; Майже 2000 нових тестів використовують алгебраїчні функції.

    На платформах IEEE 754 модуль cmath тепер обробляє спеціальні значення IEEE 754 і винятки з плаваючою комою відповідно до додатку „G“ стандарту C99.

  • A new data type in the collections module: namedtuple(typename, fieldnames) is a factory function that creates subclasses of the standard tuple whose fields are accessible by name as well as index. For example:

    >>> var_type = collections.namedtuple('variable',
    ...             'id name type size')
    >>> # Names are separated by spaces or commas.
    >>> # 'id, name, type, size' would also work.
    >>> var_type._fields
    ('id', 'name', 'type', 'size')
    
    >>> var = var_type(1, 'frequency', 'int', 4)
    >>> print var[0], var.id    # Equivalent
    1 1
    >>> print var[2], var.type  # Equivalent
    int int
    >>> var._asdict()
    {'size': 4, 'type': 'int', 'id': 1, 'name': 'frequency'}
    >>> v2 = var._replace(name='amplitude')
    >>> v2
    variable(id=1, name='amplitude', type='int', size=4)
    

    Several places in the standard library that returned tuples have been modified to return namedtuple() instances. For example, the decimal.Decimal.as_tuple() method now returns a named tuple with sign, digits, and exponent fields.

    (Надав Реймонд Геттінгер.)

  • Another change to the collections module is that the deque type now supports an optional maxlen parameter; if supplied, the deque’s size will be restricted to no more than maxlen items. Adding more items to a full deque causes old items to be discarded.

    >>> from collections import deque
    >>> dq=deque(maxlen=3)
    >>> dq
    deque([], maxlen=3)
    >>> dq.append(1); dq.append(2); dq.append(3)
    >>> dq
    deque([1, 2, 3], maxlen=3)
    >>> dq.append(4)
    >>> dq
    deque([2, 3, 4], maxlen=3)
    

    (Надав Реймонд Геттінгер.)

  • The Cookie module’s Morsel objects now support an httponly attribute. In some browsers. cookies with this attribute set cannot be accessed or manipulated by JavaScript code. (Contributed by Arvin Schnell; bpo-1638033.)

  • A new window method in the curses module, chgat(), changes the display attributes for a certain number of characters on a single line. (Contributed by Fabian Kreutz.)

    # Boldface text starting at y=0,x=21
    # and affecting the rest of the line.
    stdscr.chgat(0, 21, curses.A_BOLD)
    

    The Textbox class in the curses.textpad module now supports editing in insert mode as well as overwrite mode. Insert mode is enabled by supplying a true value for the insert_mode parameter when creating the Textbox instance.

  • The datetime module’s strftime() methods now support a %f format code that expands to the number of microseconds in the object, zero-padded on the left to six places. (Contributed by Skip Montanaro; bpo-1158.)

  • The decimal module was updated to version 1.66 of the General Decimal Specification. New features include some methods for some basic mathematical functions such as exp() and log10():

    >>> Decimal(1).exp()
    Decimal("2.718281828459045235360287471")
    >>> Decimal("2.7182818").ln()
    Decimal("0.9999999895305022877376682436")
    >>> Decimal(1000).log10()
    Decimal("3")
    

    The as_tuple() method of Decimal objects now returns a named tuple with sign, digits, and exponent fields.

    (Реалізовано Факундо Батістою та Марком Дікінсоном. Підтримку іменованих кортежів додав Реймонд Геттінгер.)

  • The difflib module’s SequenceMatcher class now returns named tuples representing matches, with a, b, and size attributes. (Contributed by Raymond Hettinger.)

  • An optional timeout parameter, specifying a timeout measured in seconds, was added to the ftplib.FTP class constructor as well as the connect() method. (Added by Facundo Batista.) Also, the FTP class’s storbinary() and storlines() now take an optional callback parameter that will be called with each block of data after the data has been sent. (Contributed by Phil Schwartz; bpo-1221598.)

  • The reduce() built-in function is also available in the functools module. In Python 3.0, the builtin has been dropped and reduce() is only available from functools; currently there are no plans to drop the builtin in the 2.x series. (Patched by Christian Heimes; bpo-1739906.)

  • Коли це можливо, модуль getpass тепер використовуватиме /dev/tty для друку підказки та читання пароля, повертаючись до стандартної помилки та стандартного введення. Якщо пароль може відтворюватися на терміналі, перед відображенням підказки друкується попередження. (Надав Грегорі П. Сміт.)

  • Функція glob.glob() тепер може повертати назви файлів у кодуванні Unicode, якщо було використано шлях у кодуванні Unicode і назви файлів у кодуванні Unicode збігаються в каталозі. (bpo-1001604)

  • Нова функція в модулі heapq, merge(iter1, iter2, ...), приймає будь-яку кількість ітерацій, які повертають дані в порядку сортування, і повертає новий генератор, який повертає вміст усіх ітератори, також у відсортованому порядку. Наприклад:

    >>> list(heapq.merge([1, 3, 5, 9], [2, 8, 16]))
    [1, 2, 3, 5, 8, 9, 16]
    

    Another new function, heappushpop(heap, item), pushes item onto heap, then pops off and returns the smallest item. This is more efficient than making a call to heappush() and then heappop().

    heapq тепер реалізовано для використання лише порівняння менше ніж, замість порівняння менше або рівно, яке використовувалося раніше. Завдяки цьому використання типу heapq відповідає методу list.sort(). (Надав Реймонд Геттінгер.)

  • An optional timeout parameter, specifying a timeout measured in seconds, was added to the httplib.HTTPConnection and HTTPSConnection class constructors. (Added by Facundo Batista.)

  • Most of the inspect module’s functions, such as getmoduleinfo() and getargs(), now return named tuples. In addition to behaving like tuples, the elements of the return value can also be accessed as attributes. (Contributed by Raymond Hettinger.)

    Some new functions in the module include isgenerator(), isgeneratorfunction(), and isabstract().

  • Модуль itertools отримав кілька нових функцій.

    izip_longest(iter1, iter2, ...[, fillvalue]) створює кортежі з кожного з елементів; якщо деякі з ітерацій коротші за інші, відсутні значення встановлюються як fillvalue. Наприклад:

    >>> tuple(itertools.izip_longest([1,2,3], [1,2,3,4,5]))
    ((1, 1), (2, 2), (3, 3), (None, 4), (None, 5))
    

    product(iter1, iter2, ..., [repeat=N]) повертає декартовий добуток наданих ітераторів, набір кортежів, що містить усі можливі комбінації елементів, що повертаються з кожного ітератора.

    >>> list(itertools.product([1,2,3], [4,5,6]))
    [(1, 4), (1, 5), (1, 6),
     (2, 4), (2, 5), (2, 6),
     (3, 4), (3, 5), (3, 6)]
    

    Необов’язковий аргумент ключового слова repeat використовується для взяття продукту iterable або набору iterables із собою, повторюваних N разів. З одним ітерованим аргументом повертаються N-кортежі:

    >>> list(itertools.product([1,2], repeat=3))
    [(1, 1, 1), (1, 1, 2), (1, 2, 1), (1, 2, 2),
     (2, 1, 1), (2, 1, 2), (2, 2, 1), (2, 2, 2)]
    

    З двома ітераціями повертаються 2N-кортежі.

    >>> list(itertools.product([1,2], [3,4], repeat=2))
    [(1, 3, 1, 3), (1, 3, 1, 4), (1, 3, 2, 3), (1, 3, 2, 4),
     (1, 4, 1, 3), (1, 4, 1, 4), (1, 4, 2, 3), (1, 4, 2, 4),
     (2, 3, 1, 3), (2, 3, 1, 4), (2, 3, 2, 3), (2, 3, 2, 4),
     (2, 4, 1, 3), (2, 4, 1, 4), (2, 4, 2, 3), (2, 4, 2, 4)]
    

    combinations(iterable, r) повертає підпослідовності довжиною r з елементів iterable.

    >>> list(itertools.combinations('123', 2))
    [('1', '2'), ('1', '3'), ('2', '3')]
    >>> list(itertools.combinations('123', 3))
    [('1', '2', '3')]
    >>> list(itertools.combinations('1234', 3))
    [('1', '2', '3'), ('1', '2', '4'),
     ('1', '3', '4'), ('2', '3', '4')]
    

    permutations(iter[, r]) повертає всі перестановки довжиною r елементів iterable. Якщо r не вказано, за замовчуванням використовуватиметься кількість елементів, створених iterable.

    >>> list(itertools.permutations([1,2,3,4], 2))
    [(1, 2), (1, 3), (1, 4),
     (2, 1), (2, 3), (2, 4),
     (3, 1), (3, 2), (3, 4),
     (4, 1), (4, 2), (4, 3)]
    

    itertools.chain(*iterables) is an existing function in itertools that gained a new constructor in Python 2.6. itertools.chain.from_iterable(iterable) takes a single iterable that should return other iterables. chain() will then return all the elements of the first iterable, then all the elements of the second, and so on.

    >>> list(itertools.chain.from_iterable([[1,2,3], [4,5,6]]))
    [1, 2, 3, 4, 5, 6]
    

    (Усі внесено Реймондом Геттінгером.)

  • The logging module’s FileHandler class and its subclasses WatchedFileHandler, RotatingFileHandler, and TimedRotatingFileHandler now have an optional delay parameter to their constructors. If delay is true, opening of the log file is deferred until the first emit() call is made. (Contributed by Vinay Sajip.)

    TimedRotatingFileHandler also has a utc constructor parameter. If the argument is true, UTC time will be used in determining when midnight occurs and in generating filenames; otherwise local time will be used.

  • До модуля math додано кілька нових функцій:

    • isinf() і isnan() визначають, чи є даний float нескінченністю (позитивною чи від’ємною) чи NaN (не числом) відповідно.

    • copysign() копіює знаковий біт числа IEEE 754, повертаючи абсолютне значення x у поєднанні зі знаковим бітом y. Наприклад, math.copysign(1, -0.0) повертає -1.0. (Надано Крістіаном Хеймсом.)

    • factorial() обчислює факториал числа. (Надав Реймонд Геттінгер; bpo-2138.)

    • fsum() додає потік чисел із ітерованого об’єкта та обережно, щоб уникнути втрати точності через використання часткових сум. (Надано Жаном Брауерсом, Реймондом Геттінгером і Марком Дікінсоном; bpo-2819.)

    • acosh(), asinh() і atanh() обчислюють обернені гіперболічні функції.

    • log1p() повертає натуральний логарифм 1+x (за основою e).

    • trunc() rounds a number toward zero, returning the closest Integral that’s between the function’s argument and zero. Added as part of the backport of PEP 3141’s type hierarchy for numbers.

  • Модуль math було покращено, щоб забезпечити більш узгоджену поведінку на різних платформах, особливо щодо обробки винятків із плаваючою комою та спеціальних значень IEEE 754.

    За можливості модуль дотримується рекомендацій стандарту C99 щодо спеціальних значень 754. Наприклад, sqrt(-1.) тепер має видавати ValueError майже на всіх платформах, тоді як sqrt(float('NaN')) має повертати NaN на всіх IEEE 754 платформи. Там, де Додаток «F» стандарту C99 рекомендує сигналізувати «ділить на нуль» або «недійсний», Python викличе ValueError. Там, де додаток «F» стандарту C99 рекомендує сигналізувати «переповнення», Python викличе OverflowError. (Див. bpo-711019 і bpo-1640.)

    (Надано Крістіаном Хеймсом і Марком Дікінсоном.)

  • mmap objects now have a rfind() method that searches for a substring beginning at the end of the string and searching backwards. The find() method also gained an end parameter giving an index at which to stop searching. (Contributed by John Lenton.)

  • The operator module gained a methodcaller() function that takes a name and an optional set of arguments, returning a callable that will call the named function on any arguments passed to it. For example:

    >>> # Equivalent to lambda s: s.replace('old', 'new')
    >>> replacer = operator.methodcaller('replace', 'old', 'new')
    >>> replacer('old wine in old bottles')
    'new wine in new bottles'
    

    (Надав Георг Брандл за пропозицією Григорія Петросяна.)

    The attrgetter() function now accepts dotted names and performs the corresponding attribute lookups:

    >>> inst_name = operator.attrgetter(
    ...        '__class__.__name__')
    >>> inst_name('')
    'str'
    >>> inst_name(help)
    '_Helper'
    

    (Надано Георгом Брандлом за пропозицією Баррі Варшави.)

  • Модуль os тепер обертає кілька нових системних викликів. fchmod(fd, mode) і fchown(fd, uid, gid) змінюють режим і право власності на відкритий файл, а lchmod(path, mode) змінює режим символічного посилання . (Надано Георгом Брандлом і Крістіаном Хаймсом.)

    chflags() and lchflags() are wrappers for the corresponding system calls (where they’re available), changing the flags set on a file. Constants for the flag values are defined in the stat module; some possible values include UF_IMMUTABLE to signal the file may not be changed and UF_APPEND to indicate that data can only be appended to the file. (Contributed by M. Levinson.)

    os.closerange(low, high) ефективно закриває всі файлові дескриптори від low до high, ігноруючи будь-які помилки та не включаючи сам high. Ця функція тепер використовується модулем subprocess для пришвидшення запуску процесів. (Надав Георг Брандл; bpo-1663329.)

  • The os.environ object’s clear() method will now unset the environment variables using os.unsetenv() in addition to clearing the object’s keys. (Contributed by Martin Horcicka; bpo-1181.)

  • Функція os.walk() тепер має параметр followlinks. Якщо встановлено значення True, він переходитиме за символічними посиланнями на каталоги та відвідуватиме вміст каталогу. Для зворотної сумісності значення параметра за замовчуванням — false. Зверніть увагу, що функція може впасти в нескінченну рекурсію, якщо є символічне посилання, яке вказує на батьківський каталог. (bpo-1273829)

  • In the os.path module, the splitext() function has been changed to not split on leading period characters. This produces better results when operating on Unix’s dot-files. For example, os.path.splitext('.ipython') now returns ('.ipython', '') instead of ('', '.ipython'). (bpo-1115886)

    Нова функція, os.path.relpath(path, start='.'), повертає відносний шлях від шляху start, якщо він надається, або від поточного робочого каталогу до пункту призначення шлях. (Надав Річард Барран; bpo-1339796.)

    У Windows os.path.expandvars() тепер розширюватиме змінні середовища, подані у формі «%var%», а «~user» буде розгорнуто до шляху до домашнього каталогу користувача. (Надав Джосія Карлсон; bpo-957650.)

  • Налагоджувач Python, наданий модулем pdb, отримав нову команду: «запустити» перезапускає програму Python, яка налагоджується, і може додатково приймати нові аргументи командного рядка для програми. (Надав Роккі Бернштейн; bpo-1393667.)

  • Функція pdb.post_mortem(), яка використовується для початку налагодження зворотного відстеження, тепер використовуватиме відстеження, яке повертає sys.exc_info(), якщо відстеження не надано. (Надав Факундо Батіста; bpo-1106316.)

  • The pickletools module now has an optimize() function that takes a string containing a pickle and removes some unused opcodes, returning a shorter pickle that contains the same data structure. (Contributed by Raymond Hettinger.)

  • A get_data() function was added to the pkgutil module that returns the contents of resource files included with an installed Python package. For example:

    >>> import pkgutil
    >>> print pkgutil.get_data('test', 'exception_hierarchy.txt')
    BaseException
     +-- SystemExit
     +-- KeyboardInterrupt
     +-- GeneratorExit
     +-- Exception
          +-- StopIteration
          +-- StandardError
     ...
    

    (Надав Пол Мур; bpo-2439.)

  • The pyexpat module’s Parser objects now allow setting their buffer_size attribute to change the size of the buffer used to hold character data. (Contributed by Achim Gaedke; bpo-1137.)

  • The queue module now provides queue variants that retrieve entries in different orders. The PriorityQueue class stores queued items in a heap and retrieves them in priority order, and LifoQueue retrieves the most recently added entries first, meaning that it behaves like a stack. (Contributed by Raymond Hettinger.)

  • The random module’s Random objects can now be pickled on a 32-bit system and unpickled on a 64-bit system, and vice versa. Unfortunately, this change also means that Python 2.6’s Random objects can’t be unpickled correctly on earlier versions of Python. (Contributed by Shawn Ligocki; bpo-1727780.)

    Нова функція triangular(low, high, mode) повертає випадкові числа за трикутним розподілом. Повернуті значення знаходяться в діапазоні від low до high, не враховуючи самого high, і з mode як значенням, що найчастіше зустрічається в розподілі. (Надано Володимиром ван дер Ланом і Раймондом Геттінгером; bpo-1681432.)

  • Довгі пошуки регулярних виразів, які виконує модуль re, перевірятимуть сигнали, які доставляються, тому трудомісткі пошуки тепер можна перервати. (Надано Джошем Хойтом і Ральфом Шміттом; bpo-846388.)

    Модуль регулярного виразу реалізовано шляхом компіляції байт-кодів для крихітної віртуальної машини, специфічної для регулярного виразу. Ненадійний код може безпосередньо створювати шкідливі рядки байт-коду та спричиняти збої, тому Python 2.6 включає верифікатор для байт-коду регулярного виразу. (Надано Гвідо ван Россумом із роботи в Google App Engine; bpo-3487.)

  • The rlcompleter module’s complete() method will now ignore exceptions triggered while evaluating a name. (Fixed by Lorenz Quack; bpo-2250.)

  • The sched module’s scheduler instances now have a read-only queue attribute that returns the contents of the scheduler’s queue, represented as a list of named tuples with the fields (time, priority, action, argument). (Contributed by Raymond Hettinger; bpo-1861.)

  • The select module now has wrapper functions for the Linux epoll() and BSD kqueue() system calls. modify() method was added to the existing poll objects; pollobj.modify(fd, eventmask) takes a file descriptor or file object and an event mask, modifying the recorded event mask for that file. (Contributed by Christian Heimes; bpo-1657.)

  • Функція shutil.copytree() тепер має додатковий аргумент ignore, який приймає об’єкт, що викликається. Цей виклик отримає кожен шлях до каталогу та список вмісту каталогу, а також поверне список імен, які будуть проігноровані, не скопійовані.

    The shutil module also provides an ignore_patterns() function for use with this new parameter. ignore_patterns() takes an arbitrary number of glob-style patterns and returns a callable that will ignore any files and directories that match any of these patterns. The following example copies a directory tree, but skips both .svn directories and Emacs backup files, which have names ending with „~“:

    shutil.copytree('Doc/library', '/tmp/library',
                    ignore=shutil.ignore_patterns('*~', '.svn'))
    

    (Надав Тарек Зіаде; bpo-2663.)

  • Інтеграція обробки сигналів із циклами обробки подій GUI, подібними до тих, що використовуються Tkinter або GTk+, давно була проблемою; більшість програм закінчується опитуванням, прокидаючись кожну частку секунди, щоб перевірити, чи відбулися якісь події GUI. Модуль signal тепер може зробити це ефективнішим. Виклик signal.set_wakeup_fd(fd) встановлює дескриптор файлу для використання; коли сигнал отримано, байт записується в цей файловий дескриптор. Існує також функція C-рівня, PySignal_SetWakeupFd(), для встановлення дескриптора.

    Event loops will use this by opening a pipe to create two descriptors, one for reading and one for writing. The writable descriptor will be passed to set_wakeup_fd(), and the readable descriptor will be added to the list of descriptors monitored by the event loop via select() or poll(). On receiving a signal, a byte will be written and the main event loop will be woken up, avoiding the need to poll.

    (Надав Адам Олсен; bpo-1583.)

    The siginterrupt() function is now available from Python code, and allows changing whether signals can interrupt system calls or not. (Contributed by Ralf Schmitt.)

    The setitimer() and getitimer() functions have also been added (where they’re available). setitimer() allows setting interval timers that will cause a signal to be delivered to the process after a specified time, measured in wall-clock time, consumed process time, or combined process+system time. (Contributed by Guilherme Polo; bpo-2240.)

  • The smtplib module now supports SMTP over SSL thanks to the addition of the SMTP_SSL class. This class supports an interface identical to the existing SMTP class. (Contributed by Monty Taylor.) Both class constructors also have an optional timeout parameter that specifies a timeout for the initial connection attempt, measured in seconds. (Contributed by Facundo Batista.)

    Також до модуля додано реалізацію протоколу LMTP (RFC 2033). LMTP використовується замість SMTP під час передачі електронної пошти між агентами, які не керують чергою пошти. (LMTP реалізовано Leif Hedstrom; bpo-957003.)

    smtplib.SMTP.starttls() now complies with RFC 3207 and forgets any knowledge obtained from the server not obtained from the TLS negotiation itself. (Patch contributed by Bill Fenner; bpo-829951.)

  • The socket module now supports TIPC (https://tipc.sourceforge.net/), a high-performance non-IP-based protocol designed for use in clustered environments. TIPC addresses are 4- or 5-tuples. (Contributed by Alberto Bertogli; bpo-1646.)

    A new function, create_connection(), takes an address and connects to it using an optional timeout value, returning the connected socket object. This function also looks up the address’s type and connects to it using IPv4 or IPv6 as appropriate. Changing your code to use create_connection() instead of socket(socket.AF_INET, ...) may be all that’s required to make your code work with IPv6.

  • The base classes in the SocketServer module now support calling a handle_timeout() method after a span of inactivity specified by the server’s timeout attribute. (Contributed by Michael Pomraning.) The serve_forever() method now takes an optional poll interval measured in seconds, controlling how often the server will check for a shutdown request. (Contributed by Pedro Werneck and Jeffrey Yasskin; bpo-742598, bpo-1193577.)

  • Модуль sqlite3, який підтримує Gerhard Häring, було оновлено з версії 2.3.2 у Python 2.5 до версії 2.4.1.

  • The struct module now supports the C99 _Bool type, using the format character '?'. (Contributed by David Remahl.)

  • The Popen objects provided by the subprocess module now have terminate(), kill(), and send_signal() methods. On Windows, send_signal() only supports the SIGTERM signal, and all these methods are aliases for the Win32 API function TerminateProcess(). (Contributed by Christian Heimes.)

  • A new variable in the sys module, float_info, is an object containing information derived from the float.h file about the platform’s floating-point support. Attributes of this object include mant_dig (number of digits in the mantissa), epsilon (smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes; bpo-1534.)

    Another new variable, dont_write_bytecode, controls whether Python writes any .pyc or .pyo files on importing a module. If this variable is true, the compiled files are not written. The variable is initially set on start-up by supplying the -B switch to the Python interpreter, or by setting the PYTHONDONTWRITEBYTECODE environment variable before running the interpreter. Python code can subsequently change the value of this variable to control whether bytecode files are written or not. (Contributed by Neal Norwitz and Georg Brandl.)

    Information about the command-line arguments supplied to the Python interpreter is available by reading attributes of a named tuple available as sys.flags. For example, the verbose attribute is true if Python was executed in verbose mode, debug is true in debugging mode, etc. These attributes are all read-only. (Contributed by Christian Heimes.)

    A new function, getsizeof(), takes a Python object and returns the amount of memory used by the object, measured in bytes. Built-in objects return correct results; third-party extensions may not, but can define a __sizeof__() method to return the object’s size. (Contributed by Robert Schuppenies; bpo-2898.)

    Тепер можна визначити поточні функції профайлера та трасувальника, викликавши sys.getprofile() і sys.gettrace(). (Надав Георг Брандл; bpo-1648.)

  • Модуль tarfile тепер підтримує tar-файли POSIX.1-2001 (pax) на додаток до форматів POSIX.1-1988 (ustar) і GNU tar, які вже підтримувалися. Типовим форматом є GNU tar; вкажіть параметр format, щоб відкрити файл в іншому форматі:

    tar = tarfile.open("output.tar", "w",
                       format=tarfile.PAX_FORMAT)
    

    Нові параметри encoding і errors визначають кодування та схему обробки помилок для перетворення символів. 'strict', 'ignore' і 'replace' є трьома стандартними способами, якими Python може обробляти помилки; 'utf-8'' — це спеціальне значення, яке замінює неправильні символи їх представленням UTF-8. (Перетворення символів відбувається через те, що формат PAX підтримує імена файлів Unicode із кодуванням UTF-8 за умовчанням.)

    The tarfile.TarFile.add() method now accepts an exclude argument that’s a function that can be used to exclude certain filenames from an archive. The function must take a filename and return true if the file should be excluded or false if it should be archived. The function is applied to both the name initially passed to add() and to the names of files in recursively added directories.

    (Усі зміни внесено Ларсом Густебелем).

  • An optional timeout parameter was added to the telnetlib.Telnet class constructor, specifying a timeout measured in seconds. (Added by Facundo Batista.)

  • Клас tempfile.NamedTemporaryFile зазвичай видаляє створений ним тимчасовий файл, коли файл закривається. Цю поведінку тепер можна змінити, передавши delete=False конструктору. (Надав Деміен Міллер; bpo-1537850.)

    A new class, SpooledTemporaryFile, behaves like a temporary file but stores its data in memory until a maximum size is exceeded. On reaching that limit, the contents will be written to an on-disk temporary file. (Contributed by Dustin J. Mitchell.)

    The NamedTemporaryFile and SpooledTemporaryFile classes both work as context managers, so you can write with tempfile.NamedTemporaryFile() as tmp: .... (Contributed by Alexander Belopolsky; bpo-2021.)

  • The test.test_support module gained a number of context managers useful for writing tests. EnvironmentVarGuard() is a context manager that temporarily changes environment variables and automatically restores them to their old values.

    Another context manager, TransientResource, can surround calls to resources that may or may not be available; it will catch and ignore a specified list of exceptions. For example, a network test may ignore certain failures when connecting to an external web site:

    with test_support.TransientResource(IOError,
                                    errno=errno.ETIMEDOUT):
        f = urllib.urlopen('https://sf.net')
        ...
    

    Finally, check_warnings() resets the warnings module’s warning filters and returns an object that will record all warning messages triggered (bpo-3781):

    with test_support.check_warnings() as wrec:
        warnings.simplefilter("always")
        # ... code that triggers a warning ...
        assert str(wrec.message) == "function is outdated"
        assert len(wrec.warnings) == 1, "Multiple warnings raised"
    

    (Надав Бретт Кеннон.)

  • The textwrap module can now preserve existing whitespace at the beginnings and ends of the newly created lines by specifying drop_whitespace=False as an argument:

    >>> S = """This  sentence  has a bunch   of
    ...   extra   whitespace."""
    >>> print textwrap.fill(S, width=15)
    This  sentence
    has a bunch
    of    extra
    whitespace.
    >>> print textwrap.fill(S, drop_whitespace=False, width=15)
    This  sentence
      has a bunch
       of    extra
       whitespace.
    >>>
    

    (Надав Дуейн Бейлі; bpo-1581073.)

  • The threading module API is being changed to use properties such as daemon instead of setDaemon() and isDaemon() methods, and some methods have been renamed to use underscores instead of camel-case; for example, the activeCount() method is renamed to active_count(). Both the 2.6 and 3.0 versions of the module support the same properties and renamed methods, but don’t remove the old methods. No date has been set for the deprecation of the old APIs in Python 3.x; the old APIs won’t be removed in any 2.x version. (Carried out by several people, most notably Benjamin Peterson.)

    The threading module’s Thread objects gained an ident property that returns the thread’s identifier, a nonzero integer. (Contributed by Gregory P. Smith; bpo-2871.)

  • The timeit module now accepts callables as well as strings for the statement being timed and for the setup code. Two convenience functions were added for creating Timer instances: repeat(stmt, setup, time, repeat, number) and timeit(stmt, setup, time, number) create an instance and call the corresponding method. (Contributed by Erik Demaine; bpo-1533909.)

  • The tkinter module now accepts lists and tuples for options, separating the elements by spaces before passing the resulting value to Tcl/Tk. (Contributed by Guilherme Polo; bpo-2906.)

  • Модуль turtle для черепахової графіки був значно вдосконалений Грегором Лінглом. Нові функції в модулі включають:

    • Краща анімація руху та обертання черепахи.

    • Control over turtle movement using the new delay(), tracer(), and speed() methods.

    • Можливість задавати нові форми для черепахи та визначати нову систему координат.

    • Turtles now have an undo() method that can roll back actions.

    • Проста підтримка реагування на події введення, такі як активність миші та клавіатури, що дає змогу писати прості ігри.

    • Файл turtle.cfg можна використовувати для налаштування початкового вигляду екрана черепахи.

    • Документаційні рядки модуля можна замінити новими документаційними рядками, перекладеними іншою мовою.

    (bpo-1513695)

  • An optional timeout parameter was added to the urllib.urlopen function and the urllib.ftpwrapper class constructor, as well as the urllib2.urlopen function. The parameter specifies a timeout measured in seconds. For example:

    >>> u = urllib2.urlopen("http://slow.example.com",
                            timeout=3)
    Traceback (most recent call last):
      ...
    urllib2.URLError: <urlopen error timed out>
    >>>
    

    (Додав Факундо Батіста.)

  • Базу даних Unicode, яку надає модуль unicodedata, оновлено до версії 5.1.0. (Оновлено Мартіном фон Льовісом; bpo-3811.)

  • The warnings module’s formatwarning() and showwarning() gained an optional line argument that can be used to supply the line of source code. (Added as part of bpo-1631171, which re-implemented part of the warnings module in C code.)

    A new function, catch_warnings(), is a context manager intended for testing purposes that lets you temporarily modify the warning filters and then restore their original values (bpo-3781).

  • The XML-RPC SimpleXMLRPCServer and DocXMLRPCServer classes can now be prevented from immediately opening and binding to their socket by passing False as the bind_and_activate constructor parameter. This can be used to modify the instance’s allow_reuse_address attribute before calling the server_bind() and server_activate() methods to open the socket and begin listening for connections. (Contributed by Peter Parente; bpo-1599845.)

    SimpleXMLRPCServer also has a _send_traceback_header attribute; if true, the exception and formatted traceback are returned as HTTP headers «X-Exception» and «X-Traceback». This feature is for debugging purposes only and should not be used on production servers because the tracebacks might reveal passwords or other sensitive information. (Contributed by Alan McIntyre as part of his project for Google’s Summer of Code 2007.)

  • The xmlrpclib module no longer automatically converts datetime.date and datetime.time to the xmlrpclib.DateTime type; the conversion semantics were not necessarily correct for all applications. Code using xmlrpclib should convert date and time instances. (bpo-1330538) The code can also handle dates before 1900 (contributed by Ralf Schmitt; bpo-2014) and 64-bit integers represented by using <i8> in XML-RPC responses (contributed by Riku Lindblad; bpo-2985).

  • The zipfile module’s ZipFile class now has extract() and extractall() methods that will unpack a single file or all the files in the archive to the current directory, or to a specified directory:

    z = zipfile.ZipFile('python-251.zip')
    
    # Unpack a single file, writing it relative
    # to the /tmp directory.
    z.extract('Python/sysmodule.c', '/tmp')
    
    # Unpack all the files in the archive.
    z.extractall()
    

    (Надав Алан Макінтайр; bpo-467924.)

    The open(), read() and extract() methods can now take either a filename or a ZipInfo object. This is useful when an archive accidentally contains a duplicated filename. (Contributed by Graham Horler; bpo-1775025.)

    Нарешті, zipfile тепер підтримує використання імен файлів Unicode для архівованих файлів. (Надав Олексій Борзенков; bpo-1734346.)

Модуль ast

Модуль ast забезпечує представлення коду Python у вигляді абстрактного синтаксичного дерева, а Армін Ронахер додав набір допоміжних функцій, які виконують різноманітні типові завдання. Вони будуть корисні для пакетів шаблонів HTML, аналізаторів коду та подібних інструментів, які обробляють код Python.

The parse() function takes an expression and returns an AST. The dump() function outputs a representation of a tree, suitable for debugging:

import ast

t = ast.parse("""
d = {}
for i in 'abcdefghijklm':
    d[i + i] = ord(i) - ord('a') + 1
print d
""")
print ast.dump(t)

Це виводить глибоко вкладене дерево:

Module(body=[
  Assign(targets=[
    Name(id='d', ctx=Store())
   ], value=Dict(keys=[], values=[]))
  For(target=Name(id='i', ctx=Store()),
      iter=Str(s='abcdefghijklm'), body=[
    Assign(targets=[
      Subscript(value=
        Name(id='d', ctx=Load()),
          slice=
          Index(value=
            BinOp(left=Name(id='i', ctx=Load()), op=Add(),
             right=Name(id='i', ctx=Load()))), ctx=Store())
     ], value=
     BinOp(left=
      BinOp(left=
       Call(func=
        Name(id='ord', ctx=Load()), args=[
          Name(id='i', ctx=Load())
         ], keywords=[], starargs=None, kwargs=None),
       op=Sub(), right=Call(func=
        Name(id='ord', ctx=Load()), args=[
          Str(s='a')
         ], keywords=[], starargs=None, kwargs=None)),
       op=Add(), right=Num(n=1)))
    ], orelse=[])
   Print(dest=None, values=[
     Name(id='d', ctx=Load())
   ], nl=True)
 ])

The literal_eval() method takes a string or an AST representing a literal expression, parses and evaluates it, and returns the resulting value. A literal expression is a Python expression containing only strings, numbers, dictionaries, etc. but no statements or function calls. If you need to evaluate an expression but cannot accept the security risk of using an eval() call, literal_eval() will handle it safely:

>>> literal = '("a", "b", {2:4, 3:8, 1:2})'
>>> print ast.literal_eval(literal)
('a', 'b', {1: 2, 2: 4, 3: 8})
>>> print ast.literal_eval('"a" + "b"')
Traceback (most recent call last):
  ...
ValueError: malformed string

The module also includes NodeVisitor and NodeTransformer classes for traversing and modifying an AST, and functions for common transformations such as changing line numbers.

The future_builtins module

Python 3.0 makes many changes to the repertoire of built-in functions, and most of the changes can’t be introduced in the Python 2.x series because they would break compatibility. The future_builtins module provides versions of these built-in functions that can be imported when writing 3.0-compatible code.

Функції цього модуля наразі включають:

  • ascii(obj): еквівалент repr(). У Python 3.0 repr() поверне рядок Unicode, тоді як ascii() поверне чистий байтовий рядок ASCII.

  • filter(predicate, iterable), map(func, iterable1, ...): версії 3.0 повертають ітератори, на відміну від вбудованих 2.x, які повертають списки.

  • hex(value), oct(value): instead of calling the __hex__() or __oct__() methods, these versions will call the __index__() method and convert the result to hexadecimal or octal. oct() will use the new 0o notation for its result.

Модуль json: Нотація об’єктів JavaScript

Новий модуль json підтримує кодування та декодування типів Python у JSON (Javascript Object Notation). JSON — це легкий формат обміну, який часто використовується у веб-додатках. Для отримання додаткової інформації про JSON відвідайте http://www.json.org.

json підтримує декодування та кодування більшості вбудованих типів Python. У наступному прикладі кодується та декодується словник:

>>> import json
>>> data = {"spam": "foo", "parrot": 42}
>>> in_json = json.dumps(data) # Encode the data
>>> in_json
'{"parrot": 42, "spam": "foo"}'
>>> json.loads(in_json) # Decode into a Python object
{"spam": "foo", "parrot": 42}

Також можна написати власні декодери та кодери для підтримки більшої кількості типів. Також підтримується швидкий друк рядків JSON.

json (спочатку називався simplejson) був написаний Бобом Іпполіто.

Модуль plistlib: аналізатор списку властивостей

Формат .plist зазвичай використовується в Mac OS X для зберігання основних типів даних (чисел, рядків, списків і словників) шляхом їх серіалізації у формат на основі XML. Це нагадує серіалізацію типів даних XML-RPC.

Незважаючи на те, що в основному використовується в Mac OS X, цей формат не має нічого специфічного для Mac, а реалізація Python працює на будь-якій платформі, яку підтримує Python, тому модуль plistlib було підвищено до стандартної бібліотеки.

Користуватися модулем просто:

import sys
import plistlib
import datetime as dt

# Create data structure
data_struct = dict(lastAccessed=dt.datetime.now(),
                   version=1,
                   categories=('Personal','Shared','Private'))

# Create string containing XML.
plist_str = plistlib.writePlistToString(data_struct)
new_struct = plistlib.readPlistFromString(plist_str)
print data_struct
print new_struct

# Write data structure to a file and read it back.
plistlib.writePlist(data_struct, '/tmp/customizations.plist')
new_struct = plistlib.readPlist('/tmp/customizations.plist')

# read/writePlist accepts file-like objects as well as paths.
plistlib.writePlist(data_struct, sys.stdout)

Покращення ctypes

Томас Хеллер продовжував підтримувати та вдосконалювати модуль ctypes.

ctypes now supports a c_bool datatype that represents the C99 bool type. (Contributed by David Remahl; bpo-1649190.)

Типи рядків, буферів і масивів ctypes мають покращену підтримку розширеного синтаксису зрізу, де надаються різні комбінації (початок, зупинка, крок). (Реалізовано Томасом Воутерсом.)

All ctypes data types now support from_buffer() and from_buffer_copy() methods that create a ctypes instance based on a provided buffer object. from_buffer_copy() copies the contents of the object, while from_buffer() will share the same memory area.

Нова угода про виклики вказує ctypes очищати змінні errno або Win32 LastError на початку кожного обгорнутого виклику. (Реалізовано Томасом Геллером; bpo-1798.)

You can now retrieve the Unix errno variable after a function call. When creating a wrapped function, you can supply use_errno=True as a keyword parameter to the DLL function and then call the module-level methods set_errno() and get_errno() to set and retrieve the error value.

The Win32 LastError variable is similarly supported by the DLL, OleDLL(), and WinDLL() functions. You supply use_last_error=True as a keyword parameter and then call the module-level methods set_last_error() and get_last_error().

The byref() function, used to retrieve a pointer to a ctypes instance, now has an optional offset parameter that is a byte count that will be added to the returned pointer.

Покращена підтримка SSL

Білл Янссен значно покращив підтримку Python 2.6 для Secure Sockets Layer, додавши новий модуль, ssl, який побудовано поверх бібліотеки OpenSSL. Цей новий модуль забезпечує більше контролю над узгодженим протоколом, використовуваними сертифікатами X.509 і має кращу підтримку для написання серверів SSL (на відміну від клієнтів) на Python. Наявну підтримку SSL у модулі socket не було видалено та продовжує працювати, хоча її буде видалено в Python 3.0.

To use the new module, you must first create a TCP connection in the usual way and then pass it to the ssl.wrap_socket() function. It’s possible to specify whether a certificate is required, and to obtain certificate info by calling the getpeercert() method.

Дивись також

Документація для модуля ssl.

Скасування та видалення

  • Рядкові винятки видалено. Спроба використати їх викликає TypeError.

  • Changes to the Exception interface as dictated by PEP 352 continue to be made. For 2.6, the message attribute is being deprecated in favor of the args attribute.

  • (3.0-режим попередження) Python 3.0 матиме реорганізовану стандартну бібліотеку, яка видалить багато застарілих модулів і перейменує інші. Python 2.6, який працює в режимі попередження 3.0, попередить про ці модулі під час їх імпорту.

    The list of deprecated modules is: audiodev, bgenlocations, buildtools, bundlebuilder, Canvas, compiler, dircache, dl, fpformat, gensuitemodule, ihooks, imageop, imgfile, linuxaudiodev, mhlib, mimetools, multifile, new, pure, statvfs, sunaudiodev, test.testall, and toaiff.

  • The gopherlib module has been removed.

  • The MimeWriter module and mimify module have been deprecated; use the email package instead.

  • The md5 module has been deprecated; use the hashlib module instead.

  • The posixfile module has been deprecated; fcntl.lockf() provides better locking.

  • The popen2 module has been deprecated; use the subprocess module.

  • The rgbimg module has been removed.

  • The sets module has been deprecated; it’s better to use the built-in set and frozenset types.

  • The sha module has been deprecated; use the hashlib module instead.

Зміни збірки та C API

Зміни в процесі збирання Python і в API C включають:

  • Python now must be compiled with C89 compilers (after 19 years!). This means that the Python source tree has dropped its own implementations of memmove() and strerror(), which are in the C89 standard library.

  • Python 2.6 можна створити за допомогою Microsoft Visual Studio 2008 (версія 9.0), і це новий компілятор за замовчуванням. Перегляньте каталог PCbuild для файлів збірки. (Реалізовано Крістіаном Хеймсом.)

  • У Mac OS X Python 2.6 можна скомпілювати як чотиристоронню універсальну збірку. Сценарій configure може приймати перемикач --with-universal-archs=[32-bit|64-bit|all], контролюючи, чи створено двійкові файли для 32-розрядних архітектур ( x86, PowerPC), 64-розрядні (x86-64 і PPC-64) або обидва. (Надав Рональд Уссорен.)

  • A new function added in Python 2.6.6, PySys_SetArgvEx(), sets the value of sys.argv and can optionally update sys.path to include the directory containing the script named by sys.argv[0] depending on the value of an updatepath parameter.

    This function was added to close a security hole for applications that embed Python. The old function, PySys_SetArgv(), would always update sys.path, and sometimes it would add the current directory. This meant that, if you ran an application embedding Python in a directory controlled by someone else, attackers could put a Trojan-horse module in the directory (say, a file named os.py) that your application would then import and run.

    If you maintain a C/C++ application that embeds Python, check whether you’re calling PySys_SetArgv() and carefully consider whether the application should be using PySys_SetArgvEx() with updatepath set to false. Note that using this function will break compatibility with Python versions 2.6.5 and earlier; if you have to continue working with earlier versions, you can leave the call to PySys_SetArgv() alone and call PyRun_SimpleString("sys.path.pop(0)\n") afterwards to discard the first sys.path component.

    Security issue reported as CVE 2008-5983; discussed in gh-50003, and fixed by Antoine Pitrou.

  • The BerkeleyDB module now has a C API object, available as bsddb.db.api. This object can be used by other C extensions that wish to use the bsddb module for their own purposes. (Contributed by Duncan Grisby.)

  • Новий інтерфейс буфера, раніше описаний у розділі PEP 3118, додає PyObject_GetBuffer() і PyBuffer_Release(), а також кілька інших функцій.

  • Python’s use of the C stdio library is now thread-safe, or at least as thread-safe as the underlying library is. A long-standing potential bug occurred if one thread closed a file object while another thread was reading from or writing to the object. In 2.6 file objects have a reference count, manipulated by the PyFile_IncUseCount() and PyFile_DecUseCount() functions. File objects can’t be closed unless the reference count is zero. PyFile_IncUseCount() should be called while the GIL is still held, before carrying out an I/O operation using the FILE * pointer, and PyFile_DecUseCount() should be called immediately after the GIL is re-acquired. (Contributed by Antoine Pitrou and Gregory P. Smith.)

  • Одночасне імпортування модулів у двох різних потоках більше не викликає взаємоблокувань; тепер це викличе ImportError. Нова функція API, PyImport_ImportModuleNoBlock(), спочатку шукатиме модуль у sys.modules, а потім намагатиметься імпортувати його після отримання блокування імпорту. Якщо блокування імпорту утримується іншим потоком, виникає ImportError. (Надано Крістіаном Хеймсом.)

  • Several functions return information about the platform’s floating-point support. PyFloat_GetMax() returns the maximum representable floating-point value, and PyFloat_GetMin() returns the minimum positive value. PyFloat_GetInfo() returns an object containing more information from the float.h file, such as "mant_dig" (number of digits in the mantissa), "epsilon" (smallest difference between 1.0 and the next largest value representable), and several others. (Contributed by Christian Heimes; bpo-1534.)

  • C functions and methods that use PyComplex_AsCComplex() will now accept arguments that have a __complex__() method. In particular, the functions in the cmath module will now accept objects with this method. This is a backport of a Python 3.0 change. (Contributed by Mark Dickinson; bpo-1675423.)

  • C API Python тепер містить дві функції для порівняння рядків без урахування регістру: PyOS_stricmp(char*, char*) і PyOS_strnicmp(char*, char*, Py_ssize_t). (Надав Крістіан Хаймес; bpo-1635.)

  • Багато розширень C визначають власний маленький макрос для додавання цілих чисел і рядків до словника модуля у функції init*. Python 2.6 нарешті визначає стандартні макроси для додавання значень до модуля, PyModule_AddStringMacro і PyModule_AddIntMacro(). (Надано Крістіаном Хеймсом.)

  • Some macros were renamed in both 3.0 and 2.6 to make it clearer that they are macros, not functions. Py_Size() became Py_SIZE(), Py_Type() became Py_TYPE(), and Py_Refcnt() became Py_REFCNT(). The mixed-case macros are still available in Python 2.6 for backward compatibility. (bpo-1629)

  • Distutils тепер розміщує створені ним розширення C в іншому каталозі під час роботи на налагодженій версії Python. (Надав Колін Вінтер; bpo-1530959.)

  • Кілька основних типів даних, таких як цілі числа та рядки, підтримують внутрішні вільні списки об’єктів, які можна повторно використовувати. Структури даних для цих вільних списків тепер дотримуються угоди про іменування: змінна завжди має назву free_list, лічильник завжди має назву numfree, а макрос Py <typename> _MAXFREELIST завжди визначено.

  • Нова ціль Makefile, «make patchcheck», готує вихідне дерево Python для створення виправлення: вона виправляє кінцеві пробіли в усіх змінених файлах .py, перевіряє, чи було змінено документацію, і повідомляє, чи Misc/ACKS і Misc/NEWS оновлено. (Надав Бретт Кеннон.)

    Інша нова ціль, «make profile-opt», компілює двійковий файл Python за допомогою оптимізації профілю GCC. Він компілює Python із увімкненим профілюванням, запускає набір тестів для отримання набору результатів профілювання, а потім компілює, використовуючи ці результати для оптимізації. (Надав Грегорі П. Сміт.)

Зміни, що стосуються порту: Windows

  • Підтримку Windows 95, 98, ME та NT4 припинено. Python 2.6 вимагає принаймні Windows 2000 SP4.

  • Новим компілятором за замовчуванням у Windows є Visual Studio 2008 (версія 9.0). Каталоги збірки для Visual Studio 2003 (версія 7.1) і 2005 (версія 8.0) переміщено в каталог PC/. Новий каталог PCbuild підтримує крос-компіляцію для X64, збірки для налагодження та керовану оптимізацію профілем (PGO). Збірки PGO приблизно на 10% швидші за звичайні. (Надано Крістіаном Хеймсом за допомогою Аморі Форже д’Арк і Мартіна фон Льовіса.)

  • The msvcrt module now supports both the normal and wide char variants of the console I/O API. The getwch() function reads a keypress and returns a Unicode value, as does the getwche() function. The putwch() function takes a Unicode character and writes it to the console. (Contributed by Christian Heimes.)

  • os.path.expandvars() тепер розгорне змінні середовища у формі «%var%», а «~user» буде розгорнуто до шляху до домашнього каталогу користувача. (Надав Джосія Карлсон; bpo-957650.)

  • The socket module’s socket objects now have an ioctl() method that provides a limited interface to the WSAIoctl() system interface.

  • The _winreg module now has a function, ExpandEnvironmentStrings(), that expands environment variable references such as %NAME% in an input string. The handle objects provided by this module now support the context protocol, so they can be used in with statements. (Contributed by Christian Heimes.)

    _winreg also has better support for x64 systems, exposing the DisableReflectionKey(), EnableReflectionKey(), and QueryReflectionKey() functions, which enable and disable registry reflection for 32-bit processes running on 64-bit systems. (bpo-1753245)

  • The msilib module’s Record object gained GetInteger() and GetString() methods that return field values as an integer or a string. (Contributed by Floris Bruynooghe; bpo-2125.)

Зміни, що стосуються порту: Mac OS X

  • Під час компіляції збірки фреймворка Python тепер ви можете вказати ім’я фреймворка, яке буде використовуватися, надавши параметр --with-framework-name= сценарію configure.

  • The macfs module has been removed. This in turn required the macostools.touched() function to be removed because it depended on the macfs module. (bpo-1490190)

  • Many other Mac OS modules have been deprecated and will be removed in Python 3.0: _builtinSuites, aepack, aetools, aetypes, applesingle, appletrawmain, appletrunner, argvemulator, Audio_mac, autoGIL, Carbon, cfmfile, CodeWarrior, ColorPicker, EasyDialogs, Explorer, Finder, FrameWork, findertools, ic, icglue, icopen, macerrors, MacOS, macfs, macostools, macresource, MiniAEFrame, Nav, Netscape, OSATerminology, pimp, PixMapWrapper, StdSuites, SystemEvents, Terminal, and terminalcommand.

Зміни, що стосуються порту: IRIX

A number of old IRIX-specific modules were deprecated and will be removed in Python 3.0: al and AL, cd, cddb, cdplayer, CL and cl, DEVICE, ERRNO, FILE, FL and fl, flp, fm, GET, GLWS, GL and gl, IN, IOCTL, jpeg, panelparser, readcd, SV and sv, torgb, videoreader, and WAIT.

Перенесення на Python 2.6

У цьому розділі перераховані раніше описані зміни та інші виправлення помилок, які можуть потребувати змін у вашому коді:

  • Класи, які не мають бути хешованими, повинні встановити __hash__ = None у своїх визначеннях, щоб вказати цей факт.

  • Рядкові винятки видалено. Спроба використати їх викликає TypeError.

  • The __init__() method of collections.deque now clears any existing contents of the deque before adding elements from the iterable. This change makes the behavior match list.__init__().

  • object.__init__() previously accepted arbitrary arguments and keyword arguments, ignoring them. In Python 2.6, this is no longer allowed and will result in a TypeError. This will affect __init__() methods that end up calling the corresponding method on object (perhaps through using super()). See bpo-1683368 for discussion.

  • The Decimal constructor now accepts leading and trailing whitespace when passed a string. Previously it would raise an InvalidOperation exception. On the other hand, the create_decimal() method of Context objects now explicitly disallows extra whitespace, raising a ConversionSyntax exception.

  • Через помилку реалізації, якщо ви передали шлях до файлу вбудованій функції __import__(), вона фактично імпортує вказаний файл. Однак це ніколи не планувалося працювати, і реалізація тепер явно перевіряє цей випадок і викликає ImportError.

  • C API: функції PyImport_Import() і PyImport_ImportModule() тепер за замовчуванням використовують абсолютний, а не відносний імпорт. Це вплине на розширення C, які імпортують інші модулі.

  • C API: типи даних розширення, які не можна хешувати, повинні визначити свій слот tp_hash як PyObject_HashNotImplemented().

  • The socket module exception socket.error now inherits from IOError. Previously it wasn’t a subclass of StandardError but now it is, through IOError. (Implemented by Gregory P. Smith; bpo-1706815.)

  • The xmlrpclib module no longer automatically converts datetime.date and datetime.time to the xmlrpclib.DateTime type; the conversion semantics were not necessarily correct for all applications. Code using xmlrpclib should convert date and time instances. (bpo-1330538)

  • (Режим попередження 3.0) Клас Exception тепер попереджає, коли до нього звертаються за допомогою доступу до фрагментів або індексу; наявність Exception поводиться як кортеж, який поступово припиняється.

  • (3.0-режим попередження) порівняння нерівності між двома словниками або двома об’єктами, які не реалізують методи порівняння, повідомляються як попередження. dict1 == dict2 все ще працює, але dict1 < dict2 поступово припиняється.

    Порівняння між клітинками, які є частиною реалізації правил визначення області дії Python, також викликають попередження, оскільки такі порівняння повністю заборонені в 3.0.

Для програм, які вбудовують Python:

  • The PySys_SetArgvEx() function was added in Python 2.6.6, letting applications close a security hole when the existing PySys_SetArgv() function was used. Check whether you’re calling PySys_SetArgv() and carefully consider whether the application should be using PySys_SetArgvEx() with updatepath set to false.

Подяки

Автор хотів би подякувати наступним людям за пропозиції, виправлення та допомогу з різними чернетками цієї статті: Георг Брандл, Стів Браун, Нік Коглан, Ральф Кордерой, Джим Джеветт, Кент Джонсон, Кріс Ламбакер, Мартін Міхлмайр, Антуан Пітру, Браян Ворнер.