Qué hay de nuevo en Python 2.3
******************************

Autor:
   A.M. Kuchling

Este artículo explica las nuevas características de Python 2.3.
Python 2.3 se publicó el 29 de julio de 2003.

Los temas principales de Python 2.3 son el pulido de algunas de las
características añadidas en la 2.2, la adición de varias mejoras
pequeñas pero útiles al núcleo del lenguaje y la ampliación de la
biblioteca estándar.  El nuevo modelo de objetos introducido en la
versión anterior se ha beneficiado de 18 meses de correcciones de
errores y de esfuerzos de optimización que han mejorado el rendimiento
de las clases de nuevo estilo.  Se han añadido algunas funciones
incorporadas, como "sum()" y "enumerate()".  El operador "in" puede
utilizarse ahora para búsquedas de subcadenas (por ejemplo, ""ab" en
"abc"" retorna "True").

Algunas de las nuevas características de la biblioteca son los tipos
de datos booleanos, de conjunto, de montón y de fecha/hora, la
posibilidad de importar módulos desde archivos con formato ZIP, el
soporte de metadatos para el tan esperado catálogo de Python, una
versión actualizada de IDLE y módulos para registrar mensajes,
envolver texto, analizar archivos CSV, procesar opciones de línea de
comandos, utilizar bases de datos BerkeleyDB... la lista de módulos
nuevos y mejorados es larga.

Este artículo no pretende proporcionar una especificación completa de
las nuevas características, sino que proporciona una visión general
conveniente.  Para obtener todos los detalles, debes consultar la
documentación de Python 2.3, como la Referencia de la Biblioteca de
Python y el Manual de Referencia de Python.  Si quieres entender la
implementación completa y los fundamentos del diseño, consulta el PEP
de una nueva característica en particular.


PEP 218: Un tipo de datos de conjunto estándar
==============================================

The new "sets" module contains an implementation of a set datatype.
The "Set" class is for mutable sets, sets that can have members added
and removed.  The "ImmutableSet" class is for sets that can't be
modified, and instances of "ImmutableSet" can therefore be used as
dictionary keys. Sets are built on top of dictionaries, so the
elements within a set must be hashable.

Aquí hay un ejemplo simple:

   >>> import sets
   >>> S = sets.Set([1,2,3])
   >>> S
   Set([1, 2, 3])
   >>> 1 in S
   True
   >>> 0 in S
   False
   >>> S.add(5)
   >>> S.remove(3)
   >>> S
   Set([1, 2, 5])
   >>>

The union and intersection of sets can be computed with the "union()"
and "intersection()" methods; an alternative notation uses the bitwise
operators "&" and "|". Mutable sets also have in-place versions of
these methods, "union_update()" and "intersection_update()".

   >>> S1 = sets.Set([1,2,3])
   >>> S2 = sets.Set([4,5,6])
   >>> S1.union(S2)
   Set([1, 2, 3, 4, 5, 6])
   >>> S1 | S2                  # Alternative notation
   Set([1, 2, 3, 4, 5, 6])
   >>> S1.intersection(S2)
   Set([])
   >>> S1 & S2                  # Alternative notation
   Set([])
   >>> S1.union_update(S2)
   >>> S1
   Set([1, 2, 3, 4, 5, 6])
   >>>

It's also possible to take the symmetric difference of two sets.  This
is the set of all elements in the union that aren't in the
intersection.  Another way of putting it is that the symmetric
difference contains all elements that are in exactly one set.  Again,
there's an alternative notation ("^"), and an in-place version with
the ungainly name "symmetric_difference_update()".

   >>> S1 = sets.Set([1,2,3,4])
   >>> S2 = sets.Set([3,4,5,6])
   >>> S1.symmetric_difference(S2)
   Set([1, 2, 5, 6])
   >>> S1 ^ S2
   Set([1, 2, 5, 6])
   >>>

There are also "issubset()" and "issuperset()" methods for checking
whether one set is a subset or superset of another:

   >>> S1 = sets.Set([1,2,3])
   >>> S2 = sets.Set([2,3])
   >>> S2.issubset(S1)
   True
   >>> S1.issubset(S2)
   False
   >>> S1.issuperset(S2)
   True
   >>>

Ver también:

  **PEP 218** - Añadiendo un tipo de objeto de conjunto incorporado
     PEP escrito por Greg V. Wilson. Implementado por Greg V. Wilson,
     Alex Martelli y GvR.


PEP 255: Generadores simples
============================

En Python 2.2, los generadores se añadieron como una característica
opcional, que se activaba mediante una directiva "from __future__
import generators".  En 2.3 los generadores ya no necesitan ser
habilitados especialmente, y ahora están siempre presentes; esto
significa que "yield" es ahora siempre una palabra clave.  El resto de
esta sección es una copia de la descripción de los generadores del
documento "What's New in Python 2.2"; si lo leíste cuando salió Python
2.2, puedes saltarte el resto de esta sección.

Sin duda estás familiarizado con cómo funcionan las llamadas a
funciones en Python o C. Cuando llamas a una función, ésta obtiene un
espacio de nombres privado donde se crean sus variables locales.
Cuando la función llega a una declaración "return", las variables
locales se destruyen y el valor resultante se retorna a quien la
llamó.  Una llamada posterior a la misma función obtendrá un nuevo
conjunto de variables locales. Pero, ¿qué pasaría si las variables
locales no se tiraran al salir de una función? ¿Qué pasaría si
pudieras reanudar la función donde la dejaste?  Esto es lo que
proporcionan los generadores; se puede pensar en ellos como funciones
reanudables.

Este es el ejemplo más sencillo de una función generadora:

   def generate_ints(N):
       for i in range(N):
           yield i

Se ha introducido una nueva palabra clave, "yield", para los
generadores.  Cualquier función que contenga una declaración "yield"
es una función generadora; esto es detectado por el compilador de
código de bits de Python que compila la función especialmente como
resultado.

Cuando se llama a una función generadora, ésta no retorna un único
valor, sino que retorna un objeto generador que soporta el protocolo
de los iteradores.  Al ejecutar la sentencia "yield", el generador
retorna el valor de "i", de forma similar a una sentencia "return".
La gran diferencia entre "yield" y una sentencia "return" es que al
llegar a una sentencia "yield" se suspende el estado de ejecución del
generador y se conservan las variables locales.  En la siguiente
llamada al método ".next()" del generador, la función se reanudará la
ejecución inmediatamente después de la sentencia "yield".  (Por
razones complicadas, la sentencia "yield" no está permitida dentro del
bloque "try" de una sentencia "try"...`; lea **PEP 255** para una
explicación completa de la interacción entre "yield" y las
excepciones)

Here's a sample usage of the "generate_ints()" generator:

   >>> gen = generate_ints(3)
   >>> gen
   <generator object at 0x8117f90>
   >>> gen.next()
   0
   >>> gen.next()
   1
   >>> gen.next()
   2
   >>> gen.next()
   Traceback (most recent call last):
     File "stdin", line 1, in ?
     File "stdin", line 2, in generate_ints
   StopIteration

También podrías escribir "for i in generate_ints(5)", o "a,b,c =
generate_ints(3)".

Dentro de una función generadora, la expresión "return" sólo puede
usarse sin un valor, y señala el final de la procesión de valores;
después el generador no puede retornar más valores. "return" con un
valor, como "return 5", es un error de sintaxis dentro de una función
generadora.  El final de los resultados del generador también puede
indicarse levantando manualmente "StopIteration", o simplemente
dejando que el flujo de ejecución caiga en el fondo de la función.

Puedes conseguir el efecto de los generadores manualmente escribiendo
tu propia clase y almacenando todas las variables locales del
generador como variables de instancia.  Por ejemplo, la devolución de
una lista de enteros podría hacerse estableciendo "self.count" a 0, y
haciendo que el método "next()" incremente "self.count" y lo retorne.
Sin embargo, para un generador medianamente complicado, escribir la
clase correspondiente sería mucho más complicado.
"Lib/test/test_generators.py" contiene varios ejemplos más
interesantes.  El más sencillo implementa un recorrido en orden de un
árbol utilizando generadores de forma recursiva

   # A recursive generator that generates Tree leaves in in-order.
   def inorder(t):
       if t:
           for x in inorder(t.left):
               yield x
           yield t.label
           for x in inorder(t.right):
               yield x

Otros dos ejemplos en "Lib/test/test_generators.py" producen
soluciones para el problema de las N reinas (colocar $N$ reinas en un
tablero de ajedrez $NxN$ de forma que ninguna reina amenace a otra) y
el recorrido del caballero (una ruta que lleva a un caballo a cada
casilla de un tablero de ajedrez $NxN$ sin visitar ninguna casilla dos
veces).

The idea of generators comes from other programming languages,
especially Icon (https://www2.cs.arizona.edu/icon/), where the idea of
generators is central.  In Icon, every expression and function call
behaves like a generator.  One example from "An Overview of the Icon
Programming Language" at
https://www2.cs.arizona.edu/icon/docs/ipd266.htm gives an idea of what
this looks like:

   sentence := "Store it in the neighboring harbor"
   if (i := find("or", sentence)) > 5 then write(i)

In Icon the "find()" function returns the indexes at which the
substring "or" is found: 3, 23, 33.  In the "if" statement, "i" is
first assigned a value of 3, but 3 is less than 5, so the comparison
fails, and Icon retries it with the second value of 23.  23 is greater
than 5, so the comparison now succeeds, and the code prints the value
23 to the screen.

Python no va tan lejos como Icon en la adopción de generadores como
concepto central.  Los generadores se consideran parte del núcleo del
lenguaje Python, pero aprenderlos o utilizarlos no es obligatorio; si
no resuelven ningún problema que tengas, siéntete libre de ignorarlos.
Una característica novedosa de la interfaz de Python en comparación
con la de Icon es que el estado de un generador se representa como un
objeto concreto (el iterador) que puede pasarse a otras funciones o
almacenarse en una estructura de datos.

Ver también:

  **PEP 255** - Generadores simples
     Escrito por Neil Schemenauer, Tim Peters, Magnus Lie Hetland.
     Implementado principalmente por Neil Schemenauer y Tim Peters,
     con otras correcciones del equipo de Python Labs.


PEP 263: Codificación del código fuente
=======================================

Los archivos fuente de Python ahora pueden declararse con diferentes
codificaciones de conjuntos de caracteres.  Las codificaciones se
declaran incluyendo un comentario con formato especial en la primera o
segunda línea del archivo fuente.  Por ejemplo, un archivo UTF-8 puede
declararse con:

   #!/usr/bin/env python
   # -*- coding: UTF-8 -*-

Sin esta declaración de codificación, la codificación por defecto
utilizada es ASCII de 7 bits. Ejecutar o importar módulos que
contengan literales de cadena con caracteres de 8 bits y que no tengan
una declaración de codificación dará lugar a un "DeprecationWarning"
señalado por Python 2.3; en 2.4 será un error de sintaxis.

La declaración de codificación sólo afecta a los literales de cadena
Unicode, que se convertirán a Unicode utilizando la codificación
especificada.  Ten en cuenta que los identificadores de Python siguen
restringidos a caracteres ASCII, por lo que no puedes tener nombres de
variables que utilicen caracteres fuera de los alfanuméricos
habituales.

Ver también:

  **PEP 263** - Definición de las codificaciones del código fuente de
  Python
     Escrito por Marc-André Lemburg y Martin von Löwis; realizado por
     Suzuki Hisao y Martin von Löwis.


PEP 273: Importar módulos desde archivos ZIP
============================================

El nuevo módulo "zipimport" añade soporte para importar módulos desde
un archivo en formato ZIP.  No es necesario importar el módulo
explícitamente; se importará automáticamente si se añade el nombre de
un archivo ZIP a "sys.path". Por ejemplo:

   amk@nyman:~/src/python$ unzip -l /tmp/example.zip
   Archive:  /tmp/example.zip
     Length     Date   Time    Name
    --------    ----   ----    ----
        8467  11-26-02 22:30   jwzthreading.py
    --------                   -------
        8467                   1 file
   amk@nyman:~/src/python$ ./python
   Python 2.3 (#1, Aug 1 2003, 19:54:32)
   >>> import sys
   >>> sys.path.insert(0, '/tmp/example.zip')  # Add .zip file to front of path
   >>> import jwzthreading
   >>> jwzthreading.__file__
   '/tmp/example.zip/jwzthreading.py'
   >>>

Una entrada en "sys.path" puede ser ahora el nombre de un archivo ZIP.
El archivo ZIP puede contener cualquier tipo de ficheros, pero sólo se
pueden importar los ficheros llamados "*.py", "*.pyc", o "*.pyo".  Si
un archivo sólo contiene ficheros "*.py", Python no intentará
modificar el archivo añadiendo el correspondiente fichero "*.pyc", lo
que significa que si un archivo ZIP no contiene ficheros "*.pyc", la
importación puede ser bastante lenta.

También se puede especificar una ruta dentro del archivo para importar
sólo de un subdirectorio; por ejemplo, la ruta "/tmp/example.zip/lib/"
sólo importaría del subdirectorio "lib/" dentro del archivo.

Ver también:

  **PEP 273** - Importación de módulos desde archivos Zip
     Escrito por James C. Ahlstrom, que también proporcionó una
     implementación. Python 2.3 sigue la especificación en **PEP
     273**, pero utiliza una implementación escrita por Just van
     Rossum que utiliza los ganchos de importación descritos en **PEP
     302**. Vea la sección PEP 302: Nuevos ganchos de importación para
     una descripción de los nuevos ganchos de importación.


PEP 277: Soporte de nombres de archivo Unicode para Windows NT
==============================================================

En Windows NT, 2000 y XP, el sistema almacena los nombres de archivo
como cadenas Unicode. Tradicionalmente, Python ha representado los
nombres de archivo como cadenas de bytes, lo cual es inadecuado porque
hace que algunos nombres de archivo sean inaccesibles.

Python now allows using arbitrary Unicode strings (within the
limitations of the file system) for all functions that expect file
names, most notably the "open()" built-in function. If a Unicode
string is passed to "os.listdir()", Python now returns a list of
Unicode strings.  A new function, "os.getcwdu()", returns the current
directory as a Unicode string.

Las cadenas de bytes siguen funcionando como nombres de archivo, y en
Windows Python las convertirá de forma transparente a Unicode
utilizando la codificación "mbcs".

Otros sistemas también permiten cadenas Unicode como nombres de
archivo, pero las convierten en cadenas de bytes antes de pasarlas al
sistema, lo que puede provocar un "UnicodeError". Las aplicaciones
pueden comprobar si se admiten cadenas Unicode arbitrarias como
nombres de archivo comprobando "os.path.supports_unicode_filenames",
un valor booleano.

En MacOS, "os.listdir()" ahora puede retornar nombres de archivo
Unicode.

Ver también:

  **PEP 277** - Soporte de nombres de archivo Unicode para Windows NT
     Escrito por Neil Hodgson; realizado por Neil Hodgson, Martin von
     Löwis y Mark Hammond.


PEP 278: Soporte universal de nuevas líneas
===========================================

Los tres principales sistemas operativos que se utilizan hoy en día
son Microsoft Windows, el sistema operativo Macintosh de Apple y los
diversos derivados de Unix.  Una pequeña molestia del trabajo entre
plataformas es que estas tres plataformas utilizan diferentes
caracteres para marcar el final de las líneas en los archivos de
texto.  Unix utiliza el salto de línea (carácter ASCII 10), MacOS
utiliza el retorno de carro (carácter ASCII 13), y Windows utiliza una
secuencia de dos caracteres de un retorno de carro más una nueva
línea.

Python's file objects can now support end of line conventions other
than the one followed by the platform on which Python is running.
Opening a file with the mode "'U'" or "'rU'" will open a file for
reading in *universal newlines* mode.  All three line ending
conventions will be translated to a "'\n'" in the strings returned by
the various file methods such as "read()" and "readline()".

Universal newline support is also used when importing modules and when
executing a file with the "execfile()" function.  This means that
Python modules can be shared between all three operating systems
without needing to convert the line-endings.

Esta función puede desactivarse al compilar Python especificando la
opción "--without-universal-newlines" al ejecutar el script
**configure** de Python.

Ver también:

  **PEP 278** - Soporte universal de nuevas líneas
     Escrito y ejecutado por Jack Jansen.


PEP 279: enumerate()
====================

Una nueva función incorporada, "enumerate()", hará que ciertos bucles
sean un poco más claros.  "enumerate(cosa)", donde *cosa* es un
iterador o una secuencia, retorna un iterador que retornará "(0,
cosa[0])", "(1, cosa[1])", "(2, cosa[2])", y así sucesivamente.

Un modismo común para cambiar cada elemento de una lista tiene el
siguiente aspecto:

   for i in range(len(L)):
       item = L[i]
       # ... compute some result based on item ...
       L[i] = result

Esto se puede reescribir usando "enumerate()" como:

   for i, item in enumerate(L):
       # ... compute some result based on item ...
       L[i] = result

Ver también:

  **PEP 279** - La función incorporada enumerate()
     Escrito y ejecutado por Raymond D. Hettinger.


PEP 282: El paquete de registro
===============================

Se ha añadido a Python 2.3 un paquete estándar para escribir
registros, "logging".  Proporciona un mecanismo potente y flexible
para generar salidas de registro que pueden ser filtradas y procesadas
de varias maneras.  Se puede utilizar un archivo de configuración
escrito en un formato estándar para controlar el comportamiento de
registro de un programa.  Python incluye manejadores que escribirán
los registros en el error estándar o en un archivo o socket, los
enviarán al registro del sistema, o incluso los enviarán por correo
electrónico a una dirección particular; por supuesto, también es
posible escribir tus propias clases de manejadores.

The "Logger" class is the primary class. Most application code will
deal with one or more "Logger" objects, each one used by a particular
subsystem of the application. Each "Logger" is identified by a name,
and names are organized into a hierarchy using "."  as the component
separator. For example, you might have "Logger" instances named
"server", "server.auth" and "server.network".  The latter two
instances are below "server" in the hierarchy.  This means that if you
turn up the verbosity for "server" or direct "server" messages to a
different handler, the changes will also apply to records logged to
"server.auth" and "server.network". There's also a root "Logger"
that's the parent of all other loggers.

Para usos sencillos, el paquete "logging" contiene algunas funciones
de conveniencia que siempre utilizan la raíz log:

   import logging

   logging.debug('Debugging information')
   logging.info('Informational message')
   logging.warning('Warning:config file %s not found', 'server.conf')
   logging.error('Error occurred')
   logging.critical('Critical error -- shutting down')

Esto produce la siguiente salida:

   WARNING:root:Warning:config file server.conf not found
   ERROR:root:Error occurred
   CRITICAL:root:Critical error -- shutting down

In the default configuration, informational and debugging messages are
suppressed and the output is sent to standard error.  You can enable
the display of informational and debugging messages by calling the
"setLevel()" method on the root logger.

Notice the "warning()" call's use of string formatting operators; all
of the functions for logging messages take the arguments "(msg, arg1,
arg2, ...)" and log the string resulting from "msg % (arg1, arg2,
...)".

There's also an "exception()" function that records the most recent
traceback.  Any of the other functions will also record the traceback
if you specify a true value for the keyword argument *exc_info*.

   def f():
       try:    1/0
       except: logging.exception('Problem recorded')

   f()

Esto produce la siguiente salida:

   ERROR:root:Problem recorded
   Traceback (most recent call last):
     File "t.py", line 6, in f
       1/0
   ZeroDivisionError: integer division or modulo by zero

Los programas un poco más avanzados utilizarán un logger distinto del
logger raíz. La función "getLogger(nombre)" se utiliza para obtener un
registro en particular, creándolo si aún no existe. "getLogger(None)"
retorna el logger raíz.

   log = logging.getLogger('server')
    ...
   log.info('Listening on port %i', port)
    ...
   log.critical('Disk full')
    ...

Log records are usually propagated up the hierarchy, so a message
logged to "server.auth" is also seen by "server" and "root", but a
"Logger" can prevent this by setting its "propagate" attribute to
"False".

There are more classes provided by the "logging" package that can be
customized.  When a "Logger" instance is told to log a message, it
creates a "LogRecord" instance that is sent to any number of different
"Handler" instances.  Loggers and handlers can also have an attached
list of filters, and each filter can cause the "LogRecord" to be
ignored or can modify the record before passing it along.  When
they're finally output, "LogRecord" instances are converted to text by
a "Formatter" class.  All of these classes can be replaced by your own
specially written classes.

Con todas estas características, el paquete "logging" debería
proporcionar suficiente flexibilidad incluso para las aplicaciones más
complicadas.  Esto es sólo un resumen incompleto de sus
características, así que por favor consulte la documentación de
referencia del paquete para todos los detalles.  La lectura de **PEP
282** también será útil.

Ver también:

  **PEP 282** - Un sistema de registro
     Escrito por Vinay Sajip y Trent Mick; implementado por Vinay
     Sajip.


PEP 285: Un tipo booleano
=========================

A Boolean type was added to Python 2.3.  Two new constants were added
to the "__builtin__" module, "True" and "False".  ("True" and "False"
constants were added to the built-ins in Python 2.2.1, but the 2.2.1
versions are simply set to integer values of 1 and 0 and aren't a
different type.)

El objeto de tipo para este nuevo tipo se denomina "bool"; su
constructor toma cualquier valor de Python y lo convierte en "True" o
"False".

   >>> bool(1)
   True
   >>> bool(0)
   False
   >>> bool([])
   False
   >>> bool( (1,) )
   True

La mayoría de los módulos de la biblioteca estándar y las funciones
incorporadas se han modificado para retornar booleanos.

   >>> obj = []
   >>> hasattr(obj, 'append')
   True
   >>> isinstance(obj, list)
   True
   >>> isinstance(obj, tuple)
   False

Los booleanos de Python se añadieron con el objetivo principal de
hacer el código más claro.  Por ejemplo, si estás leyendo una función
y te encuentras con la sentencia "return 1", podrías preguntarte si el
"1" representa un valor de verdad booleano, un índice o un coeficiente
que multiplica alguna otra cantidad.  Sin embargo, si la sentencia es
"return True", el significado del valor de retorno es bastante claro.

Los booleanos de Python *no* se añadieron en aras de una comprobación
de tipos estricta.  Un lenguaje muy estricto como Pascal también le
impediría realizar aritmética con booleanos, y requeriría que la
expresión en una declaración "if" siempre se evaluara a un resultado
booleano.  Python no es tan estricto y nunca lo será, como dice
explícitamente **PEP 285**.  Esto significa que puede utilizar
cualquier expresión en una sentencia "if", incluso las que se evalúan
a una lista o tupla o algún objeto aleatorio.  El tipo Booleano es una
subclase de la clase "int" por lo que la aritmética que utiliza un
Booleano sigue funcionando.

   >>> True + 1
   2
   >>> False + 1
   1
   >>> False * 75
   0
   >>> True * 75
   75

Para resumir "True" and "False"  en una frase: son formas alternativas
de deletrear los valores enteros 1 y 0, con la única diferencia de que
"str()" y "repr()" retornan las cadenas "Verdadero" y "Falso" en lugar
de "1" y "0".

Ver también:

  **PEP 285** - Añadir un tipo booleano
     Escrito y ejecutado por GvR.


PEP 293: Llamadas de retorno para el manejo de errores del códec
================================================================

Al codificar una cadena Unicode en una cadena de bytes, pueden
encontrarse caracteres no codificables.  Hasta ahora, Python ha
permitido especificar el procesamiento del error como "estricto"
(lanzando "UnicodeError"), "ignorar" (saltando el carácter), o
"reemplazar" (usando un signo de interrogación en la cadena de
salida), siendo "estricto" el comportamiento por defecto. Puede ser
deseable especificar un procesamiento alternativo de tales errores,
como insertar una referencia de carácter XML o una referencia de
entidad HTML en la cadena convertida.

Python tiene ahora un marco flexible para añadir diferentes
estrategias de procesamiento.  Se pueden añadir nuevos manejadores de
errores con "codecs.register_error()", y los códecs pueden acceder al
manejador de errores con "codecs.lookup_error()". Se ha añadido una
API en C equivalente para los códecs escritos en C. El gestor de
errores obtiene la información de estado necesaria, como la cadena que
se está convirtiendo, la posición en la cadena donde se ha detectado
el error y la codificación de destino.  El controlador puede entonces
lanzar una excepción o retornar una cadena de reemplazo.

Se han implementado dos manejadores de error adicionales utilizando
este marco: "backslashreplace" utiliza las comillas de barra invertida
de Python para representar los caracteres no codificables y
"xmlcharrefreplace" emite referencias de caracteres XML.

Ver también:

  **PEP 293** - Retrollamadas de manejo de errores del códec
     Escrito y ejecutado por Walter Dörwald.


PEP 301: Índice de paquetes y metadatos para Distutils
======================================================

La compatibilidad con el catálogo de Python, largamente solicitada,
hace su primera aparición en 2.3.

El corazón del catálogo es el nuevo comando **register** de Distutils.
Ejecutando "python setup.py register" se recogen los metadatos que
describen un paquete, como su nombre, versión, mantenedor,
descripción, etc., y se envían a un servidor de catálogo central.  El
catálogo resultante está disponible en https://pypi.org.

To make the catalog a bit more useful, a new optional *classifiers*
keyword argument has been added to the Distutils "setup()" function.
A list of Trove-style strings can be supplied to help classify the
software.

Aquí hay un ejemplo "setup.py" con clasificadores, escrito para que
sea compatible con las versiones más antiguas de Distutils:

   from distutils import core
   kw = {'name': "Quixote",
         'version': "0.5.1",
         'description': "A highly Pythonic Web application framework",
         # ...
         }

   if (hasattr(core, 'setup_keywords') and
       'classifiers' in core.setup_keywords):
       kw['classifiers'] = \
           ['Topic :: Internet :: WWW/HTTP :: Dynamic Content',
            'Environment :: No Input/Output (Daemon)',
            'Intended Audience :: Developers'],

   core.setup(**kw)

La lista completa de clasificadores se puede obtener ejecutando
"python setup.py register --list-classifiers".

Ver también:

  **PEP 301** - Índice de paquetes y metadatos para Distutils
     Escrito y ejecutado por Richard Jones.


PEP 302: Nuevos ganchos de importación
======================================

While it's been possible to write custom import hooks ever since the
"ihooks" module was introduced in Python 1.3, no one has ever been
really happy with it because writing new import hooks is difficult and
messy.  There have been various proposed alternatives such as the
"imputil" and "iu" modules, but none of them has ever gained much
acceptance, and none of them were easily usable from C code.

**PEP 302** borrows ideas from its predecessors, especially from
Gordon McMillan's "iu" module.  Three new items  are added to the
"sys" module:

* "sys.path_hooks" es una lista de objetos invocables; la mayoría de
  las veces serán clases.  Cada llamada toma una cadena que contiene
  una ruta y retorna un objeto importador que manejará las
  importaciones desde esta ruta o lanza una excepción "ImportError" si
  no puede manejar esta ruta.

* "sys.path_importer_cache" almacena en caché los objetos del
  importador para cada ruta, por lo que "sys.path_hooks" sólo tendrá
  que ser recorrido una vez para cada ruta.

* "sys.meta_path" es una lista de objetos importadores que se
  recorrerán antes de comprobar "sys.path".  Esta lista está
  inicialmente vacía, pero el código de usuario puede añadir objetos a
  ella.  Los módulos adicionales incorporados y congelados pueden ser
  importados por un objeto añadido a esta lista.

Los objetos importadores deben tener un único método,
"find_module(fullname, path=None)".  *fullname* será un nombre de
módulo o paquete, por ejemplo "string" o "distutils.core".
"find_module()" debe retornar un objeto cargador que tenga un único
método, "load_module(fullname)", que cree y retorne el objeto módulo
correspondiente.

Por lo tanto, el pseudocódigo de la nueva lógica de importación de
Python es algo así (simplificado un poco; véase **PEP 302** para los
detalles completos):

   for mp in sys.meta_path:
       loader = mp(fullname)
       if loader is not None:
           <module> = loader.load_module(fullname)

   for path in sys.path:
       for hook in sys.path_hooks:
           try:
               importer = hook(path)
           except ImportError:
               # ImportError, so try the other path hooks
               pass
           else:
               loader = importer.find_module(fullname)
               <module> = loader.load_module(fullname)

   # Not found!
   raise ImportError

Ver también:

  **PEP 302** - Nuevos ganchos de importación
     Escrito por Just van Rossum y Paul Moore. Implementado por Just
     van Rossum.


PEP 305: Archivos separados por comas
=====================================

Los archivos separados por comas son un formato frecuentemente
utilizado para exportar datos de bases de datos y hojas de cálculo.
Python 2.3 añade un analizador de archivos separados por comas.

El formato separado por comas es engañosamente sencillo a primera
vista:

   Costs,150,200,3.95

Leer una línea y llamar a "line.split(',')": ¿qué puede ser más
sencillo? Pero si se añaden datos de cadena que pueden contener comas,
las cosas se complican:

   "Costs",150,200,3.95,"Includes taxes, shipping, and sundry items"

Una expresión regular grande y fea puede analizar esto, pero usar el
nuevo paquete "csv" es mucho más sencillo:

   import csv

   input = open('datafile', 'rb')
   reader = csv.reader(input)
   for line in reader:
       print line

The "reader()" function takes a number of different options. The field
separator isn't limited to the comma and can be changed to any
character, and so can the quoting and line-ending characters.

Se pueden definir y registrar diferentes dialectos de archivos
separados por comas; actualmente hay dos dialectos, ambos utilizados
por Microsoft Excel. Una clase "csv.writer" independiente generará
archivos separados por comas a partir de una sucesión de tuplas o
listas, citando cadenas que contengan el delimitador.

Ver también:

  **PEP 305** - API de archivos CSV
     Escrito y realizado por Kevin Altis, Dave Cole, Andrew McNamara,
     Skip Montanaro, Cliff Wells.


PEP 307: Mejoras en Pickle
==========================

The "pickle" and "cPickle" modules received some attention during the
2.3 development cycle.  In 2.2, new-style classes could be pickled
without difficulty, but they weren't pickled very compactly; **PEP
307** quotes a trivial example where a new-style class results in a
pickled string three times longer than that for a classic class.

La solución fue inventar un nuevo protocolo pickle.  La función
"pickle.dumps()" soporta desde hace tiempo una bandera de texto o
binario.  En la versión 2.3, esta bandera se ha redefinido, pasando de
ser un booleano a un entero: 0 es el antiguo formato pickle en modo
texto, 1 es el antiguo formato binario, y ahora 2 es un nuevo formato
específico de 2.3.  Una nueva constante, "pickle.HIGHEST_PROTOCOL",
puede utilizarse para seleccionar el protocolo más elegante
disponible.

Unpickling is no longer considered a safe operation.  2.2's "pickle"
provided hooks for trying to prevent unsafe classes from being
unpickled (specifically, a "__safe_for_unpickling__" attribute), but
none of this code was ever audited and therefore it's all been ripped
out in 2.3.  You should not unpickle untrusted data in any version of
Python.

To reduce the pickling overhead for new-style classes, a new interface
for customizing pickling was added using three special methods:
"__getstate__()", "__setstate__()", and "__getnewargs__()".  Consult
**PEP 307** for the full semantics  of these methods.

Como forma de comprimir aún más los pickles, ahora es posible utilizar
códigos enteros en lugar de cadenas largas para identificar las clases
serializadas. La Python Software Foundation mantendrá una lista de
códigos estandarizados; también hay una gama de códigos para uso
privado.  Actualmente no se ha especificado ningún código.

Ver también:

  **PEP 307** - Extensiones del protocolo pickle
     Escrito y ejecutado por Guido van Rossum y Tim Peters.


Rebanadas ampliadas
===================

Desde la versión 1.4 de Python, la sintaxis de corte admite un tercer
argumento opcional "paso" o "zancada".  Por ejemplo, estas son todas
las sintaxis legales de Python: "L[1:10:2]", "L[:-1:1]", "L[::-1]".
Esto se añadió a Python a petición de los desarrolladores de Numerical
Python, que utiliza ampliamente el tercer argumento.  Sin embargo, los
tipos de secuencias de listas, tuplas y cadenas incorporados en Python
nunca han soportado esta característica, y lanzan un "TypeError" si lo
intentas. Michael Hudson ha contribuido con un parche para solucionar
este problema.

Por ejemplo, ahora puede extraer fácilmente los elementos de una lista
que tengan índices pares:

   >>> L = range(10)
   >>> L[::2]
   [0, 2, 4, 6, 8]

Los valores negativos también sirven para hacer una copia de la misma
lista en orden inverso:

   >>> L[::-1]
   [9, 8, 7, 6, 5, 4, 3, 2, 1, 0]

Esto también funciona para tuplas, arrays y cadenas:

   >>> s='abcd'
   >>> s[::2]
   'ac'
   >>> s[::-1]
   'dcba'

Si tienes una secuencia mutable, como una lista o un array, puedes
asignar o eliminar una rebanada extendida, pero hay algunas
diferencias entre la asignación a rebanadas extendidas y regulares.
La asignación a una rebanada regular se puede utilizar para cambiar la
longitud de la secuencia:

   >>> a = range(3)
   >>> a
   [0, 1, 2]
   >>> a[1:3] = [4, 5, 6]
   >>> a
   [0, 4, 5, 6]

Las rebanadas extendidas no son tan flexibles.  Cuando se asigna a una
rebanada extendida, la lista a la derecha de la declaración debe
contener el mismo número de elementos que la rebanada que está
reemplazando:

   >>> a = range(4)
   >>> a
   [0, 1, 2, 3]
   >>> a[::2]
   [0, 2]
   >>> a[::2] = [0, -1]
   >>> a
   [0, 1, -1, 3]
   >>> a[::2] = [0,1,2]
   Traceback (most recent call last):
     File "<stdin>", line 1, in ?
   ValueError: attempt to assign sequence of size 3 to extended slice of size 2

La eliminación es más sencilla:

   >>> a = range(4)
   >>> a
   [0, 1, 2, 3]
   >>> a[::2]
   [0, 2]
   >>> del a[::2]
   >>> a
   [1, 3]

One can also now pass slice objects to the "__getitem__()" methods of
the built-in sequences:

   >>> range(10).__getitem__(slice(0, 5, 2))
   [0, 2, 4]

O utilizar los objetos de corte directamente en los subíndices:

   >>> range(10)[slice(0, 5, 2)]
   [0, 2, 4]

To simplify implementing sequences that support extended slicing,
slice objects now have a method "indices(length)" which, given the
length of a sequence, returns a "(start, stop, step)" tuple that can
be passed directly to "range()". "indices()" handles omitted and out-
of-bounds indices in a manner consistent with regular slices (and this
innocuous phrase hides a welter of confusing details!).  The method is
intended to be used like this:

   class FakeSeq:
       ...
       def calc_item(self, i):
           ...
       def __getitem__(self, item):
           if isinstance(item, slice):
               indices = item.indices(len(self))
               return FakeSeq([self.calc_item(i) for i in range(*indices)])
           else:
               return self.calc_item(i)

En este ejemplo también se puede ver que el objeto incorporado "slice"
es ahora el objeto tipo para el tipo slice, y ya no es una función.
Esto es consistente con Python 2.2, donde "int", "str", etc.,
sufrieron el mismo cambio.


Otros cambios en el lenguaje
============================

Estos son todos los cambios que Python 2.3 introduce en el núcleo del
lenguaje Python.

* La expresión "yield" es ahora siempre una palabra clave, como se
  describe en la sección PEP 255: Generadores simples de este
  documento.

* Se ha añadido una nueva función incorporada "enumerate()", como se
  describe en la sección PEP 279: enumerate() de este documento.

* Se han añadido dos nuevas constantes, "True" y "False" junto con el
  tipo incorporado "bool", como se describe en la sección PEP 285: Un
  tipo booleano de este documento.

* El constructor de tipo "int()" ahora retornará un entero largo en
  lugar de lanzar un "OverflowError" cuando una cadena o un número de
  punto flotante es demasiado grande para caber en un entero.  Esto
  puede llevar al resultado paradójico de que
  "isinstance(int(expresión), int)" sea falso, pero parece poco
  probable que cause problemas en la práctica.

* Los tipos incorporados ahora soportan la sintaxis de rebanado
  extendida, como se describe en la sección Rebanadas ampliadas de
  este documento.

* Una nueva función incorporada, "suma(iterable, start=0)", suma los
  elementos numéricos en el objeto iterable y retorna su suma.
  "suma()" sólo acepta números, lo que significa que no se puede
  utilizar para concatenar un montón de cadenas. (Contribución de Alex
  Martelli)

* "list.insert(pos, valor)" solía insertar *valor* al principio de la
  lista cuando *pos* era negativo.  El comportamiento ha sido cambiado
  para ser consistente con la indexación de las rebanadas, así que
  cuando *pos* es -1 el valor será insertado antes del último
  elemento, y así sucesivamente.

* "list.index(value)", que busca *valor* dentro de la lista y retorna
  su índice, ahora toma los argumentos opcionales *start* y *stop*
  para limitar la búsqueda sólo a una parte de la lista.

* Los diccionarios tienen un nuevo método, "pop(key[, *default*])",
  que retorna el valor correspondiente a *key* y elimina ese par
  clave/valor del diccionario.  Si la clave solicitada no está
  presente en el diccionario, se retorna *default* si está
  especificada y se lanza "KeyError" si no lo está:

     >>> d = {1:2}
     >>> d
     {1: 2}
     >>> d.pop(4)
     Traceback (most recent call last):
       File "stdin", line 1, in ?
     KeyError: 4
     >>> d.pop(1)
     2
     >>> d.pop(1)
     Traceback (most recent call last):
       File "stdin", line 1, in ?
     KeyError: 'pop(): dictionary is empty'
     >>> d
     {}
     >>>

  También hay un nuevo método de clase, "dict.fromkeys(iterable,
  value)", que crea un diccionario con claves tomadas del iterador
  *iterable* suministrado y todos los valores establecidos a *value*,
  por defecto a "None".

  (Parches aportados por Raymond Hettinger)

  Además, el constructor "dict()" ahora acepta argumentos de palabras
  clave para simplificar la creación de pequeños diccionarios:

     >>> dict(red=1, blue=2, green=3, black=4)
     {'blue': 2, 'black': 4, 'green': 3, 'red': 1}

  (Contribución de Just van Rossum.)

* La expresión "assert" ya no comprueba la bandera "debug__", por lo
  que ya no se pueden desactivar las aserciones asignando a
  "__debug__". Ejecutar Python con la opción "-O" seguirá generando
  código que no ejecute ninguna aserción.

* Most type objects are now callable, so you can use them to create
  new objects such as functions, classes, and modules.  (This means
  that the "new" module can be deprecated in a future Python version,
  because you can now use the type objects available in the "types"
  module.) For example, you can create a new module object with the
  following code:

     >>> import types
     >>> m = types.ModuleType('abc','docstring')
     >>> m
     <module 'abc' (built-in)>
     >>> m.__doc__
     'docstring'

* Se ha añadido una nueva advertencia, "PendingDeprecationWarning"
  para indicar las características que están en proceso de ser
  obsoletas.  La advertencia no se imprimirá por defecto.  Para
  comprobar el uso de funciones que quedarán obsoletas en el futuro,
  proporcione "-Walways::PendingDeprecationWarning::" en la línea de
  comandos o utilice "warnings.filterwarnings()".

* Ha comenzado el proceso de desaprobación de las excepciones basadas
  en cadenas, como en "lanzamiento de "Error ocurred”".  Al lanzar una
  cadena, ahora se activará "PendingDeprecationWarning".

* El uso de "None" como nombre de una variable ahora resultará en una
  advertencia "SyntaxWarning".  En una futura versión de Python,
  "None" podría convertirse en una palabra clave.

* The "xreadlines()" method of file objects, introduced in Python 2.1,
  is no longer necessary because files now behave as their own
  iterator. "xreadlines()" was originally introduced as a faster way
  to loop over all the lines in a file, but now you can simply write
  "for line in file_obj". File objects also have a new read-only
  "encoding" attribute that gives the encoding used by the file;
  Unicode strings written to the file will be automatically  converted
  to bytes using the given encoding.

* El orden de resolución de métodos utilizado por las clases de estilo
  nuevo ha cambiado, aunque solo notará la diferencia si tiene una
  jerarquía de herencia realmente complicada. Las clases clásicas no
  se ven afectadas por este cambio. Python 2.2 originalmente usó un
  tipo topológico de los ancestros de una clase, pero 2.3 ahora usa el
  algoritmo C3 como se describe en el documento "A Monotonic
  Superclass Linearization for Dylan". Para comprender la motivación
  de este cambio, lea el artículo "Python 2.3 Method Resolution Order"
  de Michele Simionato, o lea el hilo en python-dev que comienza con
  el mensaje en https://mail.python.org/pipermail/python-
  dev/2002-October/029035.html . Samuele Pedroni fue el primero en
  señalar el problema y también implementó la solución codificando el
  algoritmo C3.

* Python runs multithreaded programs by switching between threads
  after executing N bytecodes.  The default value for N has been
  increased from 10 to 100 bytecodes, speeding up single-threaded
  applications by reducing the switching overhead.  Some multithreaded
  applications may suffer slower response time, but that's easily
  fixed by setting the limit back to a lower number using
  "sys.setcheckinterval(N)". The limit can be retrieved with the new
  "sys.getcheckinterval()" function.

* One minor but far-reaching change is that the names of extension
  types defined by the modules included with Python now contain the
  module and a "'.'" in front of the type name.  For example, in
  Python 2.2, if you created a socket and printed its "__class__",
  you'd get this output:

     >>> s = socket.socket()
     >>> s.__class__
     <type 'socket'>

  En 2.3, se obtiene esto:

     >>> s.__class__
     <type '_socket.socket'>

* Se ha eliminado una de las incompatibilidades señaladas entre las
  clases de estilo antiguo y las de estilo nuevo: ahora se pueden
  asignar a los atributos "__name__" y "__bases__" de las clases de
  estilo nuevo.  Hay algunas restricciones sobre lo que se puede
  asignar a "__bases__" en la línea de las relacionadas con la
  asignación al atributo "__class__" de una instancia.


Cambios en las cadenas de texto
-------------------------------

* El operador "in" ahora funciona de forma diferente para las cadenas.
  Antes, cuando se evaluaba "X en Y" donde *X* y *Y* eran cadenas, *X*
  sólo podía ser un único carácter. Esto ha cambiado; *X* puede ser
  una cadena de cualquier longitud, y "X en Y" retornará "True" si *X*
  es una subcadena de *Y*.  Si *X* es una cadena vacía, el resultado
  es siempre "True".

     >>> 'ab' in 'abcd'
     True
     >>> 'ad' in 'abcd'
     False
     >>> '' in 'abcd'
     True

  Note that this doesn't tell you where the substring starts; if you
  need that information, use the "find()" string method.

* The "strip()", "lstrip()", and "rstrip()" string methods now have an
  optional argument for specifying the characters to strip.  The
  default is still to remove all whitespace characters:

     >>> '   abc '.strip()
     'abc'
     >>> '><><abc<><><>'.strip('<>')
     'abc'
     >>> '><><abc<><><>\n'.strip('<>')
     'abc<><><>\n'
     >>> u'\u4000\u4001abc\u4000'.strip(u'\u4000')
     u'\u4001abc'
     >>>

  (Sugerido por Simon Brunning y aplicado por Walter Dörwald)

* The "startswith()" and "endswith()" string methods now accept
  negative numbers for the *start* and *end* parameters.

* Another new string method is "zfill()", originally a function in the
  "string" module.  "zfill()" pads a numeric string with zeros on the
  left until it's the specified width. Note that the "%" operator is
  still more flexible and powerful than "zfill()".

     >>> '45'.zfill(4)
     '0045'
     >>> '12345'.zfill(4)
     '12345'
     >>> 'goofy'.zfill(6)
     '0goofy'

  (Contribución de Walter Dörwald.)

* A new type object, "basestring", has been added. Both 8-bit strings
  and Unicode strings inherit from this type, so "isinstance(obj,
  basestring)" will return "True" for either kind of string.  It's a
  completely abstract type, so you can't create "basestring"
  instances.

* Las cadenas internas ya no son inmortales y ahora serán recolectadas
  de la forma habitual cuando la única referencia a ellas sea desde el
  diccionario interno de cadenas internas.  (Implementado por Oren
  Tirosh)


Optimizaciones
--------------

* La creación de instancias de clases de estilo nuevo se ha hecho
  mucho más rápida; ¡ahora son más rápidas que las clases clásicas!

* The "sort()" method of list objects has been extensively rewritten
  by Tim Peters, and the implementation is significantly faster.

* Multiplication of large long integers is now much faster thanks to
  an implementation of Karatsuba multiplication, an algorithm that
  scales better than the *O*(*n*^2) required for the grade-school
  multiplication algorithm.  (Original patch by Christopher A. Craig,
  and significantly reworked by Tim Peters.)

* El opcode "SET_LINENO" ha desaparecido.  Esto puede proporcionar un
  pequeño aumento de velocidad, dependiendo de la idiosincrasia de su
  compilador. Vea la sección Otros cambios y correcciones para una
  explicación más larga. (Eliminado por Michael Hudson)

* "xrange()" objects now have their own iterator, making "for i in
  xrange(n)" slightly faster than "for i in range(n)".  (Patch by
  Raymond Hettinger.)

* Se han realizado una serie de pequeños reajustes en varios puntos
  conflictivos para mejorar el rendimiento, como por ejemplo alinear
  una función o eliminar algo de código.  (Implementado principalmente
  por GvR, pero mucha gente ha contribuido con cambios individuales)

El resultado neto de las optimizaciones de la versión 2.3 es que
Python 2.3 ejecuta el benchmark pystone alrededor de un 25% f más
rápido que Python 2.2.


Módulos nuevos, mejorados y obsoletos
=====================================

Como es habitual, la biblioteca estándar de Python ha recibido una
serie de mejoras y correcciones de errores.  Aquí hay una lista
parcial de los cambios más notables, ordenados alfabéticamente por
nombre de módulo. Consulte el archivo "Misc/NEWS" en el árbol de
fuentes para obtener una lista más completa de los cambios, o busque
en los registros de CVS para obtener todos los detalles.

* El módulo "array" soporta ahora matrices de caracteres Unicode que
  utilizan el carácter de formato "'u".  Las matrices también soportan
  ahora el uso del operador de asignación "+=" para añadir el
  contenido de otra matriz, y el operador de asignación "*=" para
  repetir una matriz. (Contribución de Jason Orendorff)

* The "bsddb" module has been replaced by version 4.1.6 of the PyBSDDB
  package, providing a more complete interface to the transactional
  features of the BerkeleyDB library.

  The old version of the module has been renamed to  "bsddb185" and is
  no longer built automatically; you'll  have to edit "Modules/Setup"
  to enable it.  Note that the new "bsddb" package is intended to be
  compatible with the  old module, so be sure to file bugs if you
  discover any incompatibilities. When upgrading to Python 2.3, if the
  new interpreter is compiled with a new version of  the underlying
  BerkeleyDB library, you will almost certainly have to convert your
  database files to the new version.  You can do this fairly easily
  with the new scripts "db2pickle.py" and "pickle2db.py" which you
  will find in the distribution's "Tools/scripts" directory.  If
  you've already been using the PyBSDDB package and importing it as
  "bsddb3", you will have to change your "import" statements to import
  it as "bsddb".

* El nuevo módulo "bz2" es una interfaz para la biblioteca de
  compresión de datos bz2. Los datos comprimidos con bz2 suelen ser
  más pequeños que los correspondientes datos comprimidos con "zlib".
  (Contribución de Gustavo Niemeyer)

* Se ha añadido un conjunto de tipos de fecha/hora estándar en el
  nuevo módulo "datetime".  Consulte la siguiente sección para obtener
  más detalles.

* The Distutils "Extension" class now supports an extra constructor
  argument named *depends* for listing additional source files that an
  extension depends on.  This lets Distutils recompile the module if
  any of the dependency files are modified.  For example, if
  "sampmodule.c" includes the header file "sample.h", you would create
  the "Extension" object like this:

     ext = Extension("samp",
                     sources=["sampmodule.c"],
                     depends=["sample.h"])

  La modificación de "sample.h" haría que el módulo se recompilara.
  (Contribución de Jeremy Hylton)

* Other minor changes to Distutils: it now checks for the "CC",
  "CFLAGS", "CPP", "LDFLAGS", and "CPPFLAGS" environment variables,
  using them to override the settings in Python's configuration
  (contributed by Robert Weber).

* Previously the "doctest" module would only search the docstrings of
  public methods and functions for test cases, but it now also
  examines private ones as well.  The "DocTestSuite()" function
  creates a "unittest.TestSuite" object from a set of "doctest" tests.

* La nueva función "gc.get_referents(object)" retorna una lista de
  todos los objetos referenciados por *object*.

* The "getopt" module gained a new function, "gnu_getopt()", that
  supports the same arguments as the existing "getopt()" function but
  uses GNU-style scanning mode. The existing "getopt()" stops
  processing options as soon as a non-option argument is encountered,
  but in GNU-style mode processing continues, meaning that options and
  arguments can be mixed.  For example:

     >>> getopt.getopt(['-f', 'filename', 'output', '-v'], 'f:v')
     ([('-f', 'filename')], ['output', '-v'])
     >>> getopt.gnu_getopt(['-f', 'filename', 'output', '-v'], 'f:v')
     ([('-f', 'filename'), ('-v', '')], ['output'])

  (Contribución de Peter Åstrand.)

* Los módulos "grp", "pwd" y "resource" retornan ahora tuplas
  mejoradas:

     >>> import grp
     >>> g = grp.getgrnam('amk')
     >>> g.gr_name, g.gr_gid
     ('amk', 500)

* El módulo "gzip" ahora puede manejar archivos de más de 2 GiB.

* The new "heapq" module contains an implementation of a heap queue
  algorithm.  A heap is an array-like data structure that keeps items
  in a partially sorted order such that, for every index *k*, "heap[k]
  <= heap[2*k+1]" and "heap[k] <= heap[2*k+2]".  This makes it quick
  to remove the smallest item, and inserting a new item while
  maintaining the heap property is *O*(log *n*).  (See
  https://xlinux.nist.gov/dads//HTML/priorityque.html for more
  information about the priority queue data structure.)

  The "heapq" module provides "heappush()" and "heappop()" functions
  for adding and removing items while maintaining the heap property on
  top of some other mutable Python sequence type.  Here's an example
  that uses a Python list:

     >>> import heapq
     >>> heap = []
     >>> for item in [3, 7, 5, 11, 1]:
     ...    heapq.heappush(heap, item)
     ...
     >>> heap
     [1, 3, 5, 11, 7]
     >>> heapq.heappop(heap)
     1
     >>> heapq.heappop(heap)
     3
     >>> heap
     [5, 7, 11]

  (Contribución de Kevin O'Connor.)

* The IDLE integrated development environment has been updated using
  the code from the IDLEfork project
  (https://idlefork.sourceforge.net).  The most notable feature is
  that the code being developed is now executed in a subprocess,
  meaning that there's no longer any need for manual "reload()"
  operations. IDLE's core code has been incorporated into the standard
  library as the "idlelib" package.

* El módulo "imaplib" ahora admite IMAP sobre SSL. (Contribuido por
  Piers Lauder y Tino Lange.)

* The "itertools" contains a number of useful functions for use with
  iterators, inspired by various functions provided by the ML and
  Haskell languages.  For example, "itertools.ifilter(predicate,
  iterator)" returns all elements in the iterator for which the
  function "predicate()" returns "True", and "itertools.repeat(obj,
  N)" returns "obj" *N* times. There are a number of other functions
  in the module; see the package's reference documentation for
  details. (Contributed by Raymond Hettinger.)

* Dos nuevas funciones en el módulo "math", "degrees(rads)" y
  "radians(degs)", convierten entre radianes y grados. Otras funciones
  del módulo "math", como "math.sin()" y "math.cos()", siempre han
  requerido valores de entrada medidos en radianes. Además, se agregó
  un argumento opcional *base* a "math.log()" para facilitar el
  cálculo de logaritmos para bases distintas de "e" y "10".
  (Contribuido por Raymond Hettinger.)

* Several new POSIX functions ("getpgid()", "killpg()", "lchown()",
  "loadavg()", "major()", "makedev()", "minor()", and "mknod()") were
  added to the "posix" module that underlies the "os" module.
  (Contributed by Gustavo Niemeyer, Geert Jansen, and Denis S.
  Otkidach.)

* In the "os" module, the "*stat()" family of functions can now report
  fractions of a second in a timestamp.  Such time stamps are
  represented as floats, similar to the value returned by
  "time.time()".

  During testing, it was found that some applications will break if
  time stamps are floats.  For compatibility, when using the tuple
  interface of the "stat_result" time stamps will be represented as
  integers. When using named fields (a feature first introduced in
  Python 2.2), time stamps are still represented as integers, unless
  "os.stat_float_times()" is invoked to enable float return values:

     >>> os.stat("/tmp").st_mtime
     1034791200
     >>> os.stat_float_times(True)
     >>> os.stat("/tmp").st_mtime
     1034791200.6335014

  En Python 2.4, el valor predeterminado cambiará para devolver
  siempre flotantes.

  Los desarrolladores de aplicaciones deben habilitar esta función
  solo si todas sus bibliotecas funcionan correctamente cuando se
  enfrentan a marcas de tiempo de punto flotante o si utilizan la API
  de tuplas. Si se usa, la función debe activarse a nivel de
  aplicación en lugar de intentar habilitarla por uso.

* El módulo "optparse" contiene un nuevo analizador para argumentos de
  línea de comandos que puede convertir valores de opción a un tipo de
  Python en particular y generará automáticamente un mensaje de uso.
  Consulte la siguiente sección para obtener más detalles.

* The old and never-documented "linuxaudiodev" module has been
  deprecated, and a new version named "ossaudiodev" has been added.
  The module was renamed because the OSS sound drivers can be used on
  platforms other than Linux, and the interface has also been tidied
  and brought up to date in various ways. (Contributed by Greg Ward
  and Nicholas FitzRoy-Dale.)

* El nuevo módulo "platform" contiene una serie de funciones que
  intentan determinar varias propiedades de la plataforma en la que se
  está ejecutando. Hay funciones para obtener la arquitectura, el tipo
  de CPU, la versión del sistema operativo Windows e incluso la
  versión de distribución de Linux. (Contribución de Marc-André
  Lemburg.)

* The parser objects provided by the "pyexpat" module can now
  optionally buffer character data, resulting in fewer calls to your
  character data handler and therefore faster performance.  Setting
  the parser object's "buffer_text" attribute to "True" will enable
  buffering.

* The "sample(population, k)" function was added to the "random"
  module.  *population* is a sequence or "xrange" object containing
  the elements of a population, and "sample()" chooses *k* elements
  from the population without replacing chosen elements.  *k* can be
  any value up to "len(population)". For example:

     >>> days = ['Mo', 'Tu', 'We', 'Th', 'Fr', 'St', 'Sn']
     >>> random.sample(days, 3)      # Choose 3 elements
     ['St', 'Sn', 'Th']
     >>> random.sample(days, 7)      # Choose 7 elements
     ['Tu', 'Th', 'Mo', 'We', 'St', 'Fr', 'Sn']
     >>> random.sample(days, 7)      # Choose 7 again
     ['We', 'Mo', 'Sn', 'Fr', 'Tu', 'St', 'Th']
     >>> random.sample(days, 8)      # Can't choose eight
     Traceback (most recent call last):
       File "<stdin>", line 1, in ?
       File "random.py", line 414, in sample
           raise ValueError, "sample larger than population"
     ValueError: sample larger than population
     >>> random.sample(xrange(1,10000,2), 10)   # Choose ten odd nos. under 10000
     [3407, 3805, 1505, 7023, 2401, 2267, 9733, 3151, 8083, 9195]

  El módulo "random" ahora usa un nuevo algoritmo, el Mersenne
  Twister, implementado en C. Es más rápido y más estudiado que el
  algoritmo anterior.

  (Parches aportados por Raymond Hettinger)

* The "readline" module also gained a number of new functions:
  "get_history_item()", "get_current_history_length()", and
  "redisplay()".

* The "rexec" and "Bastion" modules have been declared dead, and
  attempts to import them will fail with a "RuntimeError".  New-style
  classes provide new ways to break out of the restricted execution
  environment provided by "rexec", and no one has interest in fixing
  them or time to do so.  If you have applications using "rexec",
  rewrite them to use something else.

  (Sticking with Python 2.2 or 2.1 will not make your applications any
  safer because there are known bugs in the "rexec" module in those
  versions.  To repeat: if you're using "rexec", stop using it
  immediately.)

* The "rotor" module has been deprecated because the  algorithm it
  uses for encryption is not believed to be secure.  If you need
  encryption, use one of the several AES Python modules that are
  available separately.

* El módulo "shutil" obtuvo una función "move(src, dest)" que mueve
  recursivamente un archivo o directorio a una nueva ubicación.

* Se agregó soporte para un manejo de señal POSIX más avanzado al
  "signal", pero luego se eliminó nuevamente, ya que resultó imposible
  hacerlo funcionar de manera confiable en todas las plataformas.

* El módulo "socket" ahora admite tiempos de espera. Puede llamar al
  método "settimeout(t)" en un objeto de socket para establecer un
  tiempo de espera de *t* seconds. Subsequent socket operations that
  take longer than *t* segundos para completar, abortará y lanzará una
  excepción "socket.timeout".

  La implementación del tiempo de espera original fue realizada por
  Tim O'Malley. Michael Gilfix lo integró en el módulo Python "socket"
  y lo guió a través de una extensa revisión. Después de que se
  registró el código, Guido van Rossum reescribió partes del mismo.
  (Este es un buen ejemplo de un proceso de desarrollo colaborativo en
  acción).

* En Windows, el módulo "socket" ahora se envía con compatibilidad con
  Secure Sockets Layer (SSL).

* The value of the C "PYTHON_API_VERSION" macro is now exposed at the
  Python level as "sys.api_version".  The current exception can be
  cleared by calling the new "sys.exc_clear()" function.

* El nuevo módulo "tarfile" permite leer y escribir en: programa:
  *tar* -format archivos de almacenamiento. (Contribución de Lars
  Gustäbel.)

* The new "textwrap" module contains functions for wrapping strings
  containing paragraphs of text.  The "wrap(text, width)" function
  takes a string and returns a list containing the text split into
  lines of no more than the chosen width.  The "fill(text, width)"
  function returns a single string, reformatted to fit into lines no
  longer than the chosen width. (As you can guess, "fill()" is built
  on top of "wrap()".  For example:

     >>> import textwrap
     >>> paragraph = "Not a whit, we defy augury: ... more text ..."
     >>> textwrap.wrap(paragraph, 60)
     ["Not a whit, we defy augury: there's a special providence in",
      "the fall of a sparrow. If it be now, 'tis not to come; if it",
      ...]
     >>> print textwrap.fill(paragraph, 35)
     Not a whit, we defy augury: there's
     a special providence in the fall of
     a sparrow. If it be now, 'tis not
     to come; if it be not to come, it
     will be now; if it be not now, yet
     it will come: the readiness is all.
     >>>

  The module also contains a "TextWrapper" class that actually
  implements the text wrapping strategy.   Both the "TextWrapper"
  class and the "wrap()" and "fill()" functions support a number of
  additional keyword arguments for fine-tuning the formatting; consult
  the module's documentation for details. (Contributed by Greg Ward.)

* The "thread" and "threading" modules now have companion modules,
  "dummy_thread" and "dummy_threading", that provide a do-nothing
  implementation of the "thread" module's interface for platforms
  where threads are not supported.  The intention is to simplify
  thread-aware modules (ones that *don't* rely on threads to run) by
  putting the following code at the top:

     try:
         import threading as _threading
     except ImportError:
         import dummy_threading as _threading

  In this example, "_threading" is used as the module name to make it
  clear that the module being used is not necessarily the actual
  "threading" module. Code can call functions and use classes in
  "_threading" whether or not threads are supported, avoiding an "if"
  statement and making the code slightly clearer.  This module will
  not magically make multithreaded code run without threads; code that
  waits for another thread to return or to do something will simply
  hang forever.

* The "time" module's "strptime()" function has long been an annoyance
  because it uses the platform C library's "strptime()"
  implementation, and different platforms sometimes have odd bugs.
  Brett Cannon contributed a portable implementation that's written in
  pure Python and should behave identically on all platforms.

* The new "timeit" module helps measure how long snippets of Python
  code take to execute.  The "timeit.py" file can be run directly from
  the command line, or the module's "Timer" class can be imported and
  used directly.  Here's a short example that figures out whether it's
  faster to convert an 8-bit string to Unicode by appending an empty
  Unicode string to it or by using the "unicode()" function:

     import timeit

     timer1 = timeit.Timer('unicode("abc")')
     timer2 = timeit.Timer('"abc" + u""')

     # Run three trials
     print timer1.repeat(repeat=3, number=100000)
     print timer2.repeat(repeat=3, number=100000)

     # On my laptop this outputs:
     # [0.36831796169281006, 0.37441694736480713, 0.35304892063140869]
     # [0.17574405670166016, 0.18193507194519043, 0.17565798759460449]

* El módulo "Tix" ha recibido varias correcciones de errores y
  actualizaciones para la versión actual del paquete Tix.

* The "Tkinter" module now works with a thread-enabled  version of
  Tcl. Tcl's threading model requires that widgets only be accessed
  from the thread in which they're created; accesses from another
  thread can cause Tcl to panic.  For certain Tcl interfaces,
  "Tkinter" will now automatically avoid this  when a widget is
  accessed from a different thread by marshalling a command, passing
  it to the correct thread, and waiting for the results.  Other
  interfaces can't be handled automatically but "Tkinter" will now
  raise an exception on such an access so that you can at least find
  out about the problem.  See https://mail.python.org/pipermail
  /python-dev/2002-December/031107.html for a more detailed
  explanation of this change.  (Implemented by Martin von Löwis.)

* Calling Tcl methods through "_tkinter" no longer  returns only
  strings. Instead, if Tcl returns other objects those objects are
  converted to their Python equivalent, if one exists, or wrapped with
  a "_tkinter.Tcl_Obj" object if no Python equivalent exists. This
  behavior can be controlled through the "wantobjects()" method of
  "tkapp" objects.

  When using "_tkinter" through the "Tkinter" module (as most Tkinter
  applications will), this feature is always activated. It should not
  cause compatibility problems, since Tkinter would always convert
  string results to Python types where possible.

  If any incompatibilities are found, the old behavior can be restored
  by setting the "wantobjects" variable in the "Tkinter" module to
  false before creating the first "tkapp" object.

     import Tkinter
     Tkinter.wantobjects = 0

  Cualquier rotura causada por este cambio debe notificarse como un
  error.

* The "UserDict" module has a new "DictMixin" class which defines all
  dictionary methods for classes that already have a minimum mapping
  interface.  This greatly simplifies writing classes that need to be
  substitutable for dictionaries, such as the classes in  the "shelve"
  module.

  Adding the mix-in as a superclass provides the full dictionary
  interface whenever the class defines "__getitem__()",
  "__setitem__()", "__delitem__()", and "keys()". For example:

     >>> import UserDict
     >>> class SeqDict(UserDict.DictMixin):
     ...     """Dictionary lookalike implemented with lists."""
     ...     def __init__(self):
     ...         self.keylist = []
     ...         self.valuelist = []
     ...     def __getitem__(self, key):
     ...         try:
     ...             i = self.keylist.index(key)
     ...         except ValueError:
     ...             raise KeyError
     ...         return self.valuelist[i]
     ...     def __setitem__(self, key, value):
     ...         try:
     ...             i = self.keylist.index(key)
     ...             self.valuelist[i] = value
     ...         except ValueError:
     ...             self.keylist.append(key)
     ...             self.valuelist.append(value)
     ...     def __delitem__(self, key):
     ...         try:
     ...             i = self.keylist.index(key)
     ...         except ValueError:
     ...             raise KeyError
     ...         self.keylist.pop(i)
     ...         self.valuelist.pop(i)
     ...     def keys(self):
     ...         return list(self.keylist)
     ...
     >>> s = SeqDict()
     >>> dir(s)      # See that other dictionary methods are implemented
     ['__cmp__', '__contains__', '__delitem__', '__doc__', '__getitem__',
      '__init__', '__iter__', '__len__', '__module__', '__repr__',
      '__setitem__', 'clear', 'get', 'has_key', 'items', 'iteritems',
      'iterkeys', 'itervalues', 'keylist', 'keys', 'pop', 'popitem',
      'setdefault', 'update', 'valuelist', 'values']

  (Parches aportados por Raymond Hettinger)

* The DOM implementation in "xml.dom.minidom" can now generate XML
  output in a particular encoding by providing an optional encoding
  argument to the "toxml()" and "toprettyxml()" methods of DOM nodes.

* The "xmlrpclib" module now supports an XML-RPC extension for
  handling nil data values such as Python's "None".  Nil values are
  always supported on unmarshalling an XML-RPC response.  To generate
  requests containing "None", you must supply a true value for the
  *allow_none* parameter when creating a "Marshaller" instance.

* The new "DocXMLRPCServer" module allows writing self-documenting
  XML-RPC servers. Run it in demo mode (as a program) to see it in
  action.   Pointing the web browser to the RPC server produces pydoc-
  style documentation; pointing xmlrpclib to the server allows
  invoking the actual methods. (Contributed by Brian Quinlan.)

* Se ha agregado soporte para nombres de dominio internacionalizados
  (RFCs 3454, 3490, 3491 y 3492). La codificación "idna" se puede
  utilizar para convertir entre un nombre de dominio Unicode y la
  codificación compatible con ASCII (ACE) de ese nombre.

     >{}>{}> u"www.Alliancefrançaise.nu".encode("idna")
     'www.xn--alliancefranaise-npb.nu'

  The "socket" module has also been extended to transparently convert
  Unicode hostnames to the ACE version before passing them to the C
  library. Modules that deal with hostnames such as "httplib" and
  "ftplib") also support Unicode host names; "httplib" also sends HTTP
  "Host" headers using the ACE version of the domain name.  "urllib"
  supports Unicode URLs with non-ASCII host names as long as the
  "path" part of the URL is ASCII only.

  Para implementar este cambio, se han agregado el módulo
  "stringprep", la herramienta "mkstringprep" y la codificación
  "punycode".


Tipo de fecha / hora
--------------------

Se agregaron tipos de fecha y hora adecuados para expresar marcas de
tiempo como módulo "datetime". Los tipos no admiten diferentes
calendarios ni muchas funciones sofisticadas, y solo se ciñen a los
conceptos básicos de la representación del tiempo.

The three primary types are: "date", representing a day, month, and
year; "time", consisting of hour, minute, and second; and "datetime",
which contains all the attributes of both "date" and "time". There's
also a "timedelta" class representing differences between two points
in time, and time zone logic is implemented by classes inheriting from
the abstract "tzinfo" class.

You can create instances of "date" and "time" by either supplying
keyword arguments to the appropriate constructor, e.g.
"datetime.date(year=1972, month=10, day=15)", or by using one of a
number of class methods.  For example, the "today()" class method
returns the current local date.

Una vez creadas, las instancias de las clases de fecha / hora son
inmutables. Hay varios métodos para producir cadenas formateadas a
partir de objetos:

   >>> import datetime
   >>> now = datetime.datetime.now()
   >>> now.isoformat()
   '2002-12-30T21:27:03.994956'
   >>> now.ctime()  # Only available on date, datetime
   'Mon Dec 30 21:27:03 2002'
   >>> now.strftime('%Y %d %b')
   '2002 30 Dec'

The "replace()" method allows modifying one or more fields  of a
"date" or "datetime" instance, returning a new instance:

   >>> d = datetime.datetime.now()
   >>> d
   datetime.datetime(2002, 12, 30, 22, 15, 38, 827738)
   >>> d.replace(year=2001, hour = 12)
   datetime.datetime(2001, 12, 30, 12, 15, 38, 827738)
   >>>

Instances can be compared, hashed, and converted to strings (the
result is the same as that of "isoformat()").  "date" and "datetime"
instances can be subtracted from each other, and added to "timedelta"
instances.  The largest missing feature is that there's no standard
library support for parsing strings and getting back a "date" or
"datetime".

Para obtener más información, consulte la documentación de referencia
del módulo. (Contribuido por Tim Peters.)


El módulo optparse
------------------

El módulo "getopt" proporciona un análisis sencillo de los argumentos
de la línea de comandos. El nuevo módulo "optparse" (originalmente
llamado Optik) proporciona un análisis de línea de comandos más
elaborado que sigue las convenciones de Unix, crea automáticamente la
salida para "--help" y puede realizar diferentes acciones para
diferentes opciones.

You start by creating an instance of "OptionParser" and telling it
what your program's options are.

   import sys
   from optparse import OptionParser

   op = OptionParser()
   op.add_option('-i', '--input',
                 action='store', type='string', dest='input',
                 help='set input filename')
   op.add_option('-l', '--length',
                 action='store', type='int', dest='length',
                 help='set maximum length of output')

Parsing a command line is then done by calling the "parse_args()"
method.

   options, args = op.parse_args(sys.argv[1:])
   print options
   print args

Esto devuelve un objeto que contiene todos los valores de las opciones
y una lista de cadenas que contienen los argumentos restantes.

Invocar el script con los distintos argumentos ahora funciona como era
de esperar. Tenga en cuenta que el argumento de longitud se convierte
automáticamente en un número entero.

   $ ./python opt.py -i data arg1
   <Values at 0x400cad4c: {'input': 'data', 'length': None}>
   ['arg1']
   $ ./python opt.py --input=data --length=4
   <Values at 0x400cad2c: {'input': 'data', 'length': 4}>
   []
   $

El mensaje de ayuda se genera automáticamente para usted:

   $ ./python opt.py --help
   usage: opt.py [options]

   options:
     -h, --help            show this help message and exit
     -iINPUT, --input=INPUT
                           set input filename
     -lLENGTH, --length=LENGTH
                           set maximum length of output
   $

Consulte la documentación del módulo para obtener más detalles.

Optik fue escrito por Greg Ward, con sugerencias de los lectores de
Getopt SIG.


Pymalloc: un asignador de objetos especializado
===============================================

Pymalloc, un asignador de objetos especializado escrito por Vladimir
Marangozov, fue una característica agregada a Python 2.1. Pymalloc
está diseñado para ser más rápido que el sistema "malloc()" y tener
menos sobrecarga de memoria para los patrones de asignación típicos de
los programas Python. El asignador utiliza la función "malloc()" de C
para obtener grandes grupos de memoria y luego satisface las
solicitudes de memoria más pequeñas de estos grupos.

En 2.1 y 2.2, pymalloc era una función experimental y no estaba
habilitada de forma predeterminada; tenía que habilitarlo
explícitamente al compilar Python proporcionando la opción "--with-
pymalloc" al script: program: *configure*. En 2.3, pymalloc ha tenido
más mejoras y ahora está habilitado de forma predeterminada; tendrá
que suministrar "--without-pymalloc" para deshabilitarlo.

Este cambio es transparente para el código escrito en Python; sin
embargo, pymalloc puede exponer errores en las extensiones C. Los
autores de los módulos de extensión C deben probar su código con
pymalloc habilitado, ya que algunos códigos incorrectos pueden causar
volcados de núcleo en tiempo de ejecución.

Hay un error particularmente común que causa problemas. Hay una serie
de funciones de asignación de memoria en la API C de Python que
anteriormente solo eran alias para "malloc()" y "free()" de la
biblioteca C, lo que significa que si llama accidentalmente a
funciones que no coinciden, el error no se notará. Cuando el asignador
de objetos está habilitado, estas funciones ya no son alias de
"malloc()" y "free()", y llamar a la función incorrecta para liberar
memoria puede generar un volcado de memoria. Por ejemplo, si la
memoria se asignó utilizando "PyObject_Malloc()", debe liberarse
utilizando "PyObject_Free()", no "free()". Algunos módulos incluidos
con Python entraron en conflicto con esto y tuvieron que ser
reparados; sin duda hay más módulos de terceros que tendrán el mismo
problema.

Como parte de este cambio, las confusas interfaces múltiples para
asignar memoria se han consolidado en dos familias de API. La memoria
asignada a una familia no debe manipularse con funciones de la otra
familia. Hay una familia para asignar fragmentos de memoria y otra
familia de funciones específicamente para asignar objetos Python.

* Para asignar y liberar una porción de memoria no distinguida, use la
  familia de "memoria sin procesar": "PyMem_Malloc()",
  "PyMem_Realloc()" y "PyMem_Free()".

* La familia de "memoria de objetos" es la interfaz para la
  instalación de pymalloc descrita anteriormente y está sesgada hacia
  un gran número de asignaciones "pequeñas": "PyObject_Malloc()",
  "PyObject_Realloc()" y "PyObject_Free()".

* To allocate and free Python objects, use the "object" family
  "PyObject_New", "PyObject_NewVar", and "PyObject_Del()".

Gracias al gran trabajo de Tim Peters, pymalloc en 2.3 también
proporciona funciones de depuración para detectar sobrescrituras de
memoria y liberaciones duplicadas en ambos módulos de extensión y en
el propio intérprete. Para habilitar este soporte, compile una versión
de depuración del intérprete de Python ejecutando: programa:
*configure* con "--with-pydebug".

Para ayudar a los escritores de extensiones, se distribuye un archivo
de encabezado "Misc/pymemcompat.h" con la fuente a Python 2.3 que
permite que las extensiones de Python usen las interfaces 2.3 para la
asignación de memoria mientras se compila con cualquier versión de
Python desde la 1.5.2. Debería copiar el archivo de la distribución
fuente de Python y empaquetarlo con la fuente de su extensión.

Ver también:

  https://hg.python.org/cpython/file/default/Objects/obmalloc.c
     Para obtener todos los detalles de la implementación de pymalloc,
     consulte los comentarios en la parte superior del archivo
     "Objects/obmalloc.c" en el código fuente de Python. El enlace
     anterior apunta al archivo dentro del navegador SVN de
     python.org.


Cambios en la API de Build y C
==============================

Los cambios en el proceso de compilación de Python y en la API de C
incluyen:

* La implementación de detección de ciclos utilizada por la
  recolección de basura ha demostrado ser estable, por lo que ahora se
  ha hecho obligatoria. Ya no puede compilar Python sin él, y el
  cambio "--with-cycle-gc" a: program: *configure* ha sido eliminado.

* Python ahora se puede construir opcionalmente como una biblioteca
  compartida ("libpython2.3.so") proporcionando "--enable-shared"
  cuando se ejecuta el script Python: program: *configure*.
  (Contribuido por Ondrej Palkovsky.)

* The "DL_EXPORT" and "DL_IMPORT" macros are now deprecated.
  Initialization functions for Python extension modules should now be
  declared using the new macro "PyMODINIT_FUNC", while the Python core
  will generally use the "PyAPI_FUNC" and "PyAPI_DATA" macros.

* El intérprete se puede compilar sin ninguna cadena de documentación
  para las funciones y módulos incorporados proporcionando "--without-
  doc-strings" al script: program: *configure*. Esto hace que el
  ejecutable de Python sea un 10% más pequeño, pero también significa
  que no puede obtener ayuda para las funciones integradas de Python.
  (Contribución de Gustavo Niemeyer.)

* The "PyArg_NoArgs()" macro is now deprecated, and code that uses it
  should be changed.  For Python 2.2 and later, the method definition
  table can specify the "METH_NOARGS" flag, signalling that there are
  no arguments, and the argument checking can then be removed.  If
  compatibility with pre-2.2 versions of Python is important, the code
  could use "PyArg_ParseTuple(args, "")" instead, but this will be
  slower than using "METH_NOARGS".

* "PyArg_ParseTuple()" acepta caracteres de nuevo formato para varios
  tamaños de enteros sin signo: "B" para unsigned char, "H" para
  unsigned short int, "I" para unsigned int, y "K" para unsigned long
  long.

* Se agregó una nueva función, "PyObject_DelItemString(mapping, char
  *key)", como abreviatura de "PyObject_DelItem(mapping,
  PyString_New(key))".

* Los objetos de archivo ahora administran su búfer de cadena interno
  de manera diferente, incrementándolo exponencialmente cuando es
  necesario. Esto da como resultado que las pruebas de referencia en
  "Lib/test/test_bufio.py" se aceleren considerablemente (de 57
  segundos a 1,7 segundos, según una medición).

* It's now possible to define class and static methods for a C
  extension type by setting either the "METH_CLASS" or "METH_STATIC"
  flags in a method's "PyMethodDef" structure.

* Python ahora incluye una copia del código fuente del analizador XML
  de Expat, eliminando cualquier dependencia de una versión del
  sistema o instalación local de Expat.

* If you dynamically allocate type objects in your extension, you
  should be aware of a change in the rules relating to the
  "__module__" and "__name__" attributes.  In summary, you will want
  to ensure the type's dictionary contains a "'__module__'" key;
  making the module name the part of the type name leading up to the
  final period will no longer have the desired effect.  For more
  detail, read the API reference documentation or the  source.


Cambios específicos del puerto
------------------------------

Support for a port to IBM's OS/2 using the EMX runtime environment was
merged into the main Python source tree.  EMX is a POSIX emulation
layer over the OS/2 system APIs.  The Python port for EMX tries to
support all the POSIX-like capability exposed by the EMX runtime, and
mostly succeeds; "fork()" and "fcntl()" are restricted by the
limitations of the underlying emulation layer.  The standard OS/2
port, which uses IBM's Visual Age compiler, also gained support for
case-sensitive import semantics as part of the integration of the EMX
port into CVS.  (Contributed by Andrew MacIntyre.)

En MacOS, la mayoría de los módulos de la caja de herramientas tienen
vínculos débiles para mejorar la compatibilidad con versiones
anteriores. Esto significa que los módulos ya no dejarán de cargarse
si falta una rutina en la versión actual del sistema operativo. En su
lugar, llamar a la rutina que falta lanzará una excepción.
(Contribuido por Jack Jansen.)

Los archivos de especificaciones de RPM, que se encuentran en el
directorio "Misc/RPM/" en la distribución fuente de Python, se
actualizaron para la versión 2.3. (Contribución de Sean
Reifschneider.)

Otras plataformas nuevas ahora compatibles con Python incluyen AtheOS
(http://www.atheos.cx/), GNU / Hurd y OpenVMS.


Otros cambios y correcciones
============================

Como de costumbre, hubo un montón de otras mejoras y correcciones de
errores esparcidas por todo el árbol de fuentes. Una búsqueda en los
registros de cambios de CVS encuentra que se aplicaron 523 parches y
se corrigieron 514 errores entre Python 2.2 y 2.3. Es probable que
ambas cifras estén subestimadas.

Algunos de los cambios más notables son:

* Si se establece la variable de entorno "PYTHONINSPECT", el
  intérprete de Python ingresará al indicador interactivo después de
  ejecutar un programa de Python, como si Python hubiera sido invocado
  con la opción "-i". La variable de entorno se puede configurar antes
  de ejecutar el intérprete de Python, o el programa Python puede
  configurarla como parte de su ejecución.

* El script "regrtest.py" ahora proporciona una forma de permitir
  "todos los recursos excepto *foo*". Un nombre de recurso pasado a la
  opción "-u" ahora se puede prefijar con un guión ("'-'") para
  significar "eliminar este recurso". Por ejemplo, la opción
  '"-uall,-bsddb"' podría usarse para habilitar el uso de todos los
  recursos excepto "bsddb".

* Las herramientas utilizadas para crear la documentación ahora
  funcionan tanto en Cygwin como en Unix.

* Se ha eliminado el código de operación "SET_LINENO". En la noche de
  los tiempos, este código de operación era necesario para producir
  números de línea en rastreos y admitir funciones de rastreo (para,
  por ejemplo, "pdb"). Desde Python 1.5, los números de línea en los
  rastreos se han calculado utilizando un mecanismo diferente que
  funciona con "python -O". Para Python 2.3, Michael Hudson implementó
  un esquema similar para determinar cuándo llamar a la función de
  seguimiento, eliminando por completo la necesidad de "SET_LINENO".

  Sería difícil detectar cualquier diferencia resultante del código
  Python, aparte de una ligera aceleración cuando Python se ejecuta
  sin "-O".

  C extensions that access the "f_lineno" field of frame objects
  should instead call "PyCode_Addr2Line(f->f_code, f->f_lasti)". This
  will have the added effect of making the code work as desired under
  "python -O" in earlier versions of Python.

  A nifty new feature is that trace functions can now assign to the
  "f_lineno" attribute of frame objects, changing the line that will
  be executed next.  A "jump" command has been added to the "pdb"
  debugger taking advantage of this new feature. (Implemented by
  Richie Hindle.)


Portar a Python 2.3
===================

Esta sección enumera los cambios descritos anteriormente que pueden
requerir cambios en su código:

* "yield" ahora es siempre una palabra clave; si se usa como nombre de
  variable en su código, se debe elegir un nombre diferente.

* Para cadenas, *X* and *Y*, ASDF00 now works if *X* tiene más de un
  carácter.

* El constructor de tipo "int()" ahora retornará un entero largo en
  lugar de lanzar un "OverflowError" cuando una cadena o un número de
  punto flotante es demasiado grande para caber en un entero.  Esto
  puede llevar al resultado paradójico de que
  "isinstance(int(expresión), int)" sea falso, pero parece poco
  probable que cause problemas en la práctica.

* Si tiene cadenas Unicode que contienen caracteres de 8 bits, debe
  declarar la codificación del archivo (UTF-8, Latin-1 o lo que sea)
  agregando un comentario en la parte superior del archivo. Consulte
  la sección PEP 263: Codificación del código fuente para obtener más
  información.

* Calling Tcl methods through "_tkinter" no longer  returns only
  strings. Instead, if Tcl returns other objects those objects are
  converted to their Python equivalent, if one exists, or wrapped with
  a "_tkinter.Tcl_Obj" object if no Python equivalent exists.

* Grandes literales octales y hexadecimales como "0xffffffff" ahora
  activan un "FutureWarning". Actualmente se almacenan como números de
  32 bits y dan como resultado un valor negativo, pero en Python 2.4
  se convertirán en enteros largos positivos.

  Hay varias formas de corregir esta advertencia. Si realmente
  necesita un número positivo, simplemente agregue un "L" al final del
  literal. Si está tratando de obtener un entero de 32 bits con bits
  bajos establecidos y ha usado previamente una expresión como "~(1 <<
  31)", probablemente sea más claro comenzar con todos los bits
  establecidos y borrar los bits superiores deseados. Por ejemplo,
  para borrar solo el bit superior (bit 31), puede escribir
  "0xffffffffL &~(1L<<31)".

* Ya no puede deshabilitar las aserciones asignando a "__debug__".

* The Distutils "setup()" function has gained various new keyword
  arguments such as *depends*.  Old versions of the Distutils will
  abort if passed unknown keywords.  A solution is to check for the
  presence of the new "get_distutil_options()" function in your
  "setup.py" and only uses the new keywords with a version of the
  Distutils that supports them:

     from distutils import core

     kw = {'sources': 'foo.c', ...}
     if hasattr(core, 'get_distutil_options'):
         kw['depends'] = ['foo.h']
     ext = Extension(**kw)

* El uso de "None" como nombre de una variable ahora resultará en una
  advertencia "SyntaxWarning".  En una futura versión de Python,
  "None" podría convertirse en una palabra clave.

* Los nombres de los tipos de extensión definidos por los módulos
  incluidos con Python ahora contienen el módulo y un "'.'" delante
  del nombre del tipo.


Agradecimientos
===============

El autor desea agradecer a las siguientes personas por ofrecer
sugerencias, correcciones y ayuda con varios borradores de este
artículo: Jeff Bauer, Simon Brunning, Brett Cannon, Michael Chermside,
Andrew Dalke, Scott David Daniels, Fred L. Drake, Jr., David Fraser,
Kelly Gerber, Raymond Hettinger, Michael Hudson, Chris Lambert, Detlef
Lannert, Martin von Löwis, Andrew MacIntyre, Lalo Martins, Chad
Netzer, Gustavo Niemeyer, Neal Norwitz, Hans Nowak, Chris Reedy,
Francesco Ricciardi, Vinay Sajip, Neil Schemenauer, Roman Suzi, Jason
Tishler, Just van Rossum.
