Decoradores y generadores
Dos palabras que asustan en las entrevistas de trabajo, y que en el fondo son ideas simples.
Decorators and generators
Two words that sound scary in job interviews, and are actually simple ideas underneath.
Una función normal con return calcula todo y lo entrega de golpe. Un
generador usa yield en vez de return, y entrega
los valores de a uno, solo cuando se le piden.
A normal function with return computes everything and hands it over at once. A
generator uses yield instead of return, and hands
out values one at a time, only when asked.
Esto te va a sonar familiar: llevas usando algo parecido a un generador desde el primer
tutorial de bucles. range(1000000) no crea un millón de números en memoria: los
va entregando uno por uno, a medida que el bucle los pide.
This will sound familiar: you have been using something generator-like since the very first
loops lesson. range(1000000) does not create a million numbers in memory: it
hands them out one by one, as the loop asks for them.
Un decorador es una función que recibe otra función, le agrega un
comportamiento extra, y devuelve la versión mejorada. La marca @ es solo un
atajo para aplicarlo.
A decorator is a function that takes another function, adds extra
behaviour, and returns the improved version. The @ mark is just a shortcut to
apply it.
Fíjate: saludar nunca se enteró de que la están
anunciando. El decorador agrega comportamiento sin tocar una sola línea de la
función original.
Notice: saludar never knew it was being announced.
The decorator adds behaviour without touching a single line of the original
function.
Este es uno de los usos más comunes en código real: medir cuánto se demora una función, sin ensuciarla con código de medición por dentro.
This is one of the most common real-world uses: measuring how long a function takes, without cluttering it with timing code inside.
Desde print() hasta decoradores: variables, listas y diccionarios, funciones,
clases, archivos, JSON, fechas, expresiones regulares, generadores. Con esto tienes las
herramientas para leer prácticamente cualquier código Python que te encuentres, y para empezar
un proyecto propio de verdad.
Si te interesa el otro lado —dibujar, animar, hacer juegos en el navegador— ahí está el curso de JavaScript. Vas a reconocer casi todas las ideas; solo cambia cómo se escriben.
From print() to decorators: variables, lists and dictionaries, functions,
classes, files, JSON, dates, regular expressions, generators. With this you have the tools to
read practically any Python code you come across, and to start a real project of your own.
If the other side interests you — drawing, animating, making browser games — there is the JavaScript course. You will recognise almost every idea; only the writing changes.