Новое в версиях Python

2007-12-10 at 01:42 | In devel, review | Leave a Comment
Tags: , , ,

Недавно пробовал делать разные вещи с интерпретаторами Jython 2.2 и CPtyhon 2.5. Поскольку порой не так просто вспомнить, что же добавлялось в различных версиях языка Python, я решил составить список основных изменений на основе документации по Python. Начиная с версии 2.3 список довольно подробный, а для более ранних версий легко находимой информации не так много.

  • 2.5 (2006-09)
    • Условные выражения
    • Частичное вычисление функций, пакет functools
    • Абсолютный и относительный импорт (absolute_import из __future__)
    • Объединённый try/except/finally
    • Передача значений в генераторы (val = yield i)
    • Оператор (statement) with (with_statement из __future__), протокол управления контекстом, модуль contextlib
    • Исключения как классы в новом стиле, изменения в иерархии исключений
    • Пакеты ctypes, ElementTree, hashlib, sqlite3, wsgiref
    • Другие небольшие изменения
  • 2.4 (2004-11)
    • Встроенные объекты set и frozenset
    • Генераторы как выражения
    • Декораторы функций
    • Обратная итерация (reversed())
    • Типы Decimal, Context, пакет decimal
    • Многострочные операторы (statements) import со скобками
    • Параметры key и reverse метода list.sort()
    • Другие небольшие изменения
  • 2.3 (2003-07)
    • Стандартный тип Set, пакет sets
    • Простые генераторы (yield)
    • Кодировки исходников
    • Универсальный перенос строк (режим открытия файлов "U")
    • Функции еnumerate(), sum()
    • Булевский тип (bool)
    • Расширенный слайсинг всех типов
    • Пакеты logging, csv
    • Другие небольшие изменения
  • 2.2 (2001-12)
    • Унификация типов (на C) и классов
    • Метаклассы, протокол описателей
    • Простые генераторы (generators из __future__)
    • Другие изменения
  • 2.0 (2000-10)
    • Юникодовые строки
    • Выделение списка (list comprehension)
    • Дополняющие присваивания
    • Методы у типа str
    • Сборка мусора для циклических ссылок
    • Другие изменения
  • 1.4 (1996-10)
    • Аргументы-ключевые слова
    • Встроенный тип complex
    • Искажение имён для инкапсуляции
    • Другие изменения
  • 1.0 (1994-01)
    • Элементы функционального программирования (lambda, map(), filter(), reduce())
    • Другие изменения
  • 0.9 (1991)
    • Классы с наследованием
    • Обработка исключений
    • Встроенные типы list, dict, str, …

Calculating MD5 Checksum of Ubuntu 7.10 ISO Image in Python

2007-10-19 at 02:39 | In devel, fun, lang:en | 4 Comments
Tags: , , , ,

I like the Python programming language and use it on a daily basis. To give you an example of such a usage, I’m going to calculate the MD5 checksum of a fresh Ubuntu 7.10 ISO image I’ve downloaded from a mirror site. It is needed in order to make sure that no accidental or malicious modifications have been made by the mirror maintainers or computer crackers. Another (standard) way of performing such a task is installing and using some kind of an MD5 software tool on your computer. But it’s no fun to do that, so let’s program this task in Python :)

This easiest way of calculating the checksum in Python is:

from md5 import md5
fname = "ubuntu-7.10-desktop-i386.iso"
s = md5(open(fname, "rb").read()).hexdigest()
print "md5 checksum: %s" % s

It’s quite easy, isn’t it? :) But unfortunately it’s way too inefficient, because this code has to allocate all the ISO image in memory (700+ MB) while reading it from the file.

Let’s read the ISO image file by relatively small blocks updating the MD5 checksum after every read:

from md5 import md5
fname = "ubuntu-7.10-desktop-i386.iso"
block_size = 0x10000
def upd(m, data):
  m.update(data)
  return m
fd = open(fname, "rb")
try:
  contents = iter(lambda: fd.read(block_size), "")
  m = reduce(upd, contents, md5())
  print "md5 checksum: %s" % m.hexdigest()
finally:
  fd.close()

By the way, if you’re wondering why we can “update” the checksum, see the MD5 hash algorithm; briefly because MD5 operates on independent 512-bit chunks of data that are reduced using addition modulo 232. One more comment: the code looks a bit functional, but in fact there are lots of destructive updates here.

You can compare your results with an appropriate MD5 checksum at the Ubuntu homepage.

Upd: For those people who are just looking for the MD5 checksum value of ubuntu-7.10-desktop-i386.iso, the value is: d2334dbba7313e9abc8c7c072d2af09c.

Multi-threaded map() for Python

2007-09-05 at 04:39 | In devel, lang:en, talk | 8 Comments
Tags: , ,

The idea of multi-processing map() for Python is quite nice. And what about multi-threaded one? Threads usually cause less overhead than processes. If a mapping function is quite side-effect free (even if it does some HTTP GETs — they are idempotent), you don’t rely on a parallel execution model you’ve selected. And when it isn’t, then such an approach is error-prone. I’ve implemented a very simple threaded exception-aware map() using one thread per call. This is the basic usage scenario:

@measured
def single_threaded():
  return [urlopen(url) for x in range(count)]

@measured
def multi_threaded():
  return map(lambda x: urlopen(url), range(count))

ps_s = single_threaded()
ps_m = multi_threaded()

The results for url = "http://ya.ru/" and count = 1000:

single_threaded() is finished in 121.333 s
multi_threaded() is finished in 29.692 s

A multi-threaded map() is rather useful, isn’t it?

P. S. The first exception in a map() thread will be re-raised (with its traceback) in the main thread while others will be suppressed.

Главное о Internet Protocol Multicast

2006-06-05 at 19:03 | In devel | Leave a Comment
Tags: , , , , , ,

Blog at WordPress.com. | Theme: Pool by Borja Fernandez.
Entries and comments feeds.