Changeset 89
- Timestamp:
- 19/07/09 16:57:35 (4 years ago)
- File:
-
- 1 edited
-
trunk/traducidos/stdlib.rst (modified) (2 diffs)
Legend:
- Unmodified
- Added
- Removed
-
trunk/traducidos/stdlib.rst
r88 r89 226 226 .. _tut-performance-measurement: 227 227 228 Performance Measurement 228 Medición de rendimiento 229 229 ======================= 230 230 231 Some Python users develop a deep interest in knowing the relative performance of 232 different approaches to the same problem. Python provides a measurement tool 233 that answers those questions immediately. 234 235 For ejemplo, it may be tempting to use the tuple packing and unpacking feature 236 instead of the traditional approach to swapping arguments. The :mod:`timeit` 237 module quickly demonstrates a modest performance advantage:: 231 Algunos usuarios de Python desarrollan un profundo interés en saber el 232 rendimiento relativo de las diferentes soluciones al mismo problema. Python 233 provee una herramienta de medición que responde esas preguntas inmediatamente. 234 235 Por ejemplo, puede ser tentador usar la característica de empaquetamiento y 236 desempaquetamiento de las tuplas en lugar de la solución tradicional para 237 intercambiar argumentos. El módulo :mod:`timeit` muestra rapidamente una 238 modesta ventaja de rendimiento:: 238 239 239 240 >>> from timeit import Timer … … 243 244 0.54962537085770791 244 245 245 In contrast to :mod:`timeit`'s fine level of granularity, the :mod:`profile` and 246 :mod:`pstats` modules provide tools for identifying time critical sections in 247 larger blocks of code.246 En contraste con el fino nivel de granularidad del módulo :mod:`timeit`, los 247 módulos :mod:`profile` y :mod:`pstats` proveen herramientas para identificar 248 secciones críticas de tiempo en bloques de código más grandes. 248 249 249 250 250 251 .. _tut-quality-control: 251 252 252 Quality Control 253 =============== 254 255 One approach for developing high quality software is to write tests for each 256 function as it is developed and to run those tests frequently during the 257 development process. 258 259 The :mod:`doctest` module provides a tool for scanning a module and validating 260 tests embedded in a program's docstrings. Test construction is as simple as 261 cutting-and-pasting a typical call along with its results into the docstring. 262 This improves the documentation by providing the user with an ejemplo and it 263 allows the doctest module to make sure the code remains true to the 264 documentation:: 265 266 def average(values): 267 """Computes the arithmetic mean of a list of numbers. 268 269 >>> print average([20, 30, 70]) 253 Control de calidad 254 ================== 255 256 Una forma para desarrollar software de alta calidad es escribir pruebas para 257 cada función mientras se la desarrolla, y correr esas pruebas frecuentemente 258 durante el proceso de desarrollo. 259 260 El módulo :mod:`doctest` provee una herramienta para revisar un módulo y 261 validar las pruebas integradas en las cadenas de documentación (o *docstring*) 262 del programa. La construcción de las pruebas es tan sencillo como cortar y 263 pegar una ejecución típica junto con sus resultados en los docstrings. Esto 264 mejora la documentación al proveer al usuario un ejemplo y permite que el 265 módulo :mod:`doctest` se asegure que el código permanece fiel a la 266 documentación:: 267 268 def promedio(valores): 269 """Calcula la media aritmética de una lista de números. 270 271 >>> print promedio([20, 30, 70]) 270 272 40.0 271 273 """ 272 return sum(val ues, 0.0) / len(values)274 return sum(valores, 0.0) / len(valores) 273 275 274 276 import doctest 275 doctest.testmod() # automatically validate the embedded tests276 277 The :mod:`unittest` module is not as effortless as the :mod:`doctest` module,278 but it allows a more comprehensive set of tests to be maintained in a separate 279 file::277 doctest.testmod() # valida automáticamente las pruebas integradas 278 279 El módulo :mod:`unittest` necesita más esfuerzo que el módulo :mod:`doctest`, 280 pero permite que se mantenga en un archivo separado un conjunto más comprensivo 281 de pruebas:: 280 282 281 283 import unittest 282 284 283 class Test StatisticalFunctions(unittest.TestCase):284 285 def test_ average(self):286 self.assertEqual( average([20, 30, 70]), 40.0)287 self.assertEqual(round( average([1, 5, 7]), 1), 4.3)288 self.assertRaises(ZeroDivisionError, average, [])289 self.assertRaises(TypeError, average, 20, 30, 70)290 291 unittest.main() # Calling from the command line invokes all tests285 class TestFuncionesEstadisticas(unittest.TestCase): 286 287 def test_promedio(self): 288 self.assertEqual(promedio([20, 30, 70]), 40.0) 289 self.assertEqual(round(promedio([1, 5, 7]), 1), 4.3) 290 self.assertRaises(ZeroDivisionError, promedio, []) 291 self.assertRaises(TypeError, promedio, 20, 30, 70) 292 293 unittest.main() # llamarlo de la linea de comandos ejecuta todas las pruebas 292 294 293 295 294 296 .. _tut-batteries-included: 295 297 296 Batteries Included 297 ================== 298 299 Python has a "batteries included" philosophy. This is best seen through the300 sophisticated and robust capabilities of its larger packages. For ejemplo:301 302 * The :mod:`xmlrpclib` and :mod:`SimpleXMLRPCServer` modules make implementing303 remote procedure calls into an almost trivial task. Despite the modules304 names, no direct knowledge or handling of XML is needed.305 306 * The :mod:`email` package is a library for managing email messages, including 307 MIME and other RFC 2822-based message documents. Unlike :mod:`smtplib` and 308 :mod:`poplib` which actually send and receive messages, the email package has309 a complete toolset for building or decoding complex message structures310 (including attachments) and for implementing internet encoding and header311 protocols.312 313 * The :mod:`xml.dom` and :mod:`xml.sax` packages provide robust support for 314 parsing this popular data interchange format. Likewise, the :mod:`csv` module 315 supports direct reads and writes in a common database format. Together, these 316 modules and packages greatly simplify data interchange between python317 applications and other tools.318 319 * Internationalization is supported by a number of modules including 320 :mod:`gettext`, :mod:`locale`, and the :mod:`codecs` package. 321 322 298 Las pilas incluidas 299 =================== 300 301 Python tiene una filosofía de "pilas incluidas". Esto se ve mejor en las 302 capacidades robustas y sofisticadas de sus paquetes más grandes. Por ejemplo: 303 304 * Los módulos :mod:`xmlrpclib` y :mod:`SimpleXMLRPCServer` hacen que 305 implementar llamadas a procedimientos remotos sea una tarea trivial. A 306 pesar de los nombres de los módulos, no se necesita conocimiento directo 307 o manejo de XML. 308 309 * El paquete :mod:`email` es una biblioteca para manejar mensajes de mail, 310 incluyendo MIME y otros mensajes basados en RFC 2822. Al contrario de 311 :mod:`smtplib` y :mod:`poplib` que en realidad envían y reciben mensajes, 312 el paquete :mod:`email` tiene un conjunto de herramientas completo para 313 construir y decodificar estructuras complejas de mensajes (incluyendo 314 adjuntos) y para implementar protocolos de cabecera y codificación de 315 Internet). 316 317 * Los paquetes :mod:`xml.dom` y :mod:`xml.sax` proveen un robusto soporte para 318 analizar este popular formato de intercambio de datos. Asimismo, el módulo 319 :mod:`csv` soporta lecturas y escrituras directas en un formato común de base 320 de datos. Juntos, estos módulos y paquetes simplifican enormemente el 321 intercambio de datos entre aplicaciones Python y otras herramientas. 322 323 * Se soporta la internacionalización a través de varios módulos, incluyendo 324 :mod:`gettext`, :mod:`locale`, y el paquete :mod:`codecs`.
Note: See TracChangeset
for help on using the changeset viewer.
![(please configure the [header_logo] section in trac.ini)](/python-tutorial/chrome/site/your_project_logo.png)