Upgrade to Pro
— share decks privately, control downloads, hide ads and more …
Speaker Deck
Features
Speaker Deck
PRO
Sign in
Sign up for free
Search
Search
Python Idiomático
Search
Sponsored
·
Ship Features Fearlessly
Turn features on and off without deploys. Used by thousands of Ruby developers.
→
Alejandro Gómez
October 20, 2013
Programming
160
2
Share
Python Idiomático
Alejandro Gómez
October 20, 2013
Other Decks in Programming
See All in Programming
ついに来た!本格的なマルチクラウド時代の Google Cloud
maroon1st
0
420
PicoRuby for IoT: Connecting to the Cloud with MQTT
yuuu
2
770
cloudnative conference 2026 flyle
azihsoyn
0
180
From Formal Specification to Property Based Test
ohbarye
0
2.5k
エラー処理の温故知新 / history of error handling technic
ryotanakaya
7
1.9k
t *testing.T は どこからやってくるの?
otakakot
1
930
「OSSがあるなら自作するな」は AI時代も正しいか ── Build vs Adopt の新しい判断基準
kumorn5s
7
2.6k
Liberating Ruby's Parser from Lexer Hacks
ydah
2
2.7k
HTML-Aware ERB: The Path to Reactive Rendering @ RubyKaigi 2026, Hakodate, Japan
marcoroth
0
700
SREに優しいTerraform構成 modulesとstateの組み方
hiyanger
2
170
KMP × Kotlin 2.3 - How Android Got Slower While iOS Builds Improved by 47%
rio432
0
180
開発とはなにか、Essenceカーネルで見えるもの
ukin0k0
0
160
Featured
See All Featured
Introduction to Domain-Driven Design and Collaborative software design
baasie
1
780
Lightning talk: Run Django tests with GitHub Actions
sabderemane
0
180
A Soul's Torment
seathinner
6
2.8k
Have SEOs Ruined the Internet? - User Awareness of SEO in 2025
akashhashmi
0
340
How to optimise 3,500 product descriptions for ecommerce in one day using ChatGPT
katarinadahlin
PRO
1
3.6k
Why You Should Never Use an ORM
jnunemaker
PRO
61
9.8k
Avoiding the “Bad Training, Faster” Trap in the Age of AI
tmiket
0
140
Max Prin - Stacking Signals: How International SEO Comes Together (And Falls Apart)
techseoconnect
PRO
0
160
The Web Performance Landscape in 2024 [PerfNow 2024]
tammyeverts
12
1.1k
Evolution of real-time – Irina Nazarova, EuRuKo, 2024
irinanazarova
9
1.3k
Building an army of robots
kneath
306
46k
Exploring the relationship between traditional SERPs and Gen AI search
raygrieselhuber
PRO
2
3.9k
Transcript
@dialelo | github.com/alejandrogomez Python Idiomático
Idiomático Perteneciente o conforme al modo de expresión de un
lenguaje (de programación).
import this
from __future__ import print_function
Unpacking
☹ favorite_color = [0xBA, 0xDA, 0x55] red = favorite_color[0] green
= favorite_color[1] blue = favorite_color[2]
☺ favorite_color = [0xBA, 0xDA, 0x55] red, green, blue =
favorite_color
3 head, *body, tail = range(5) # head == 0
# body == [1, 2, 3] # tail == 4
Slices
☹ person_info = ('Alejandro', 19, 12, 1988, '#BADA55') person =
Person(person_info[0], person_info[1:4], person_info[4])
☺ person_info = ('Alejandro', 19, 12, 1988, '#BADA55') NAME =
slice(0, 1) BIRTH_DATE = slice(1, 4) FAVORITE_COLOR = slice(4, 5) person = Person(person_info[NAME], person_info[BIRTH_DATE], person_info[FAVORITE_COLOR])
Strings
☹ family_members = 'Mikel' family_members += ', Ángel' family_members +=
', Isabel'
☺ names = ('Mikel', 'Ángel', 'Isabel') family_members = ', '.join(names)
Iteración Con índice
colors = ['red', 'green', 'blue']
☹ for i in range(len(colors)): print( colors[{}] : {} .format(i,
colors[i])) “ ”
☺ for i, color in enumerate(colors): print( colors[{}] : {}
.format(i, colors)) “ ”
Iteración A la inversa
☹ for color in colors[::-1]: print(color)
☺ for color in reversed(colors): print(color)
Iteración En orden
☺ for color in sorted(colors): print(color)
• ¿Necesitas definir el orden? – Prefiere key a cmp
– key sólo se llama una vez por elemento – cmp compara pares de elementos, no está en Python 3
☺ for color in sorted(colors, key=len): print(color)
from functools import cmp_to_key @cmp_to_key def my_comparison(a, b): # ...
Iteración iter
• iter tiene dos formas – iter(collection) → iterador –
iter(callable, sentinel) → iterador
☹ while True: value = read_value() if value is None:
break else: do_something(value)
☺ for value in iter(read_value, None): do_something(value)
Diccionarios Iterar
d = { 'red': 0xBA, 'green': 0xDA, 'blue': 0x55 }
# `for` itera sobre las claves for k in d: print(k)
☹☹ for k in d: print( {} : {} .format(k,
d[k])) “ ”
☹ for k, v in d.items(): print( {} : {}
.format(k, v)) “ ”
☺ for k, v in d.iteritems(): print( {} : {}
.format(k, v)) “ ”
3 for k, v in d.items(): print( {} : {}
.format(k, v)) “ ”
Diccionarios Construir
colors = ['red', 'green', 'blue'] values = [0xBA, 0xDA, 0x55]
☹ d = dict(zip(colors, values))
☺ from itertools import izip d = dict(izip(colors, values))
☺ from itertools import izip d = {c: v for
(c, v) in izip(colors, values)}
Diccionarios Combinar
one = { 'foo': 42 } another = { 'bar':
None, 'baz': 8 } yet_another = { 'foo': 1, 'baz': 0 }
☹ merged = {} for d in (one, another, yet_another):
merged.update(d)
3 from collections import ChainMap d = ChainMap(one, another, yet_another)
Django from django.utils.datastructures import MergeDict # funciona al revés que
`collections.ChainMap` ☹ d = MergeDict(yet_another, another, one)
☺ from itertools import izip d = {c: v for
(c, v) in izip(colors, values)}
Funciones λ
people = [{ 'name': 'Zoe' }, { 'name': 'Bob' },
{ 'name': 'Alice' }]
☹ for p in sorted(people, key=lambda p: p['name']): print(p)
☺ from operators import itemgetter for p in sorted(people, key=itemgetter('name')):
print(p)
Funciones Argumentos
results = search('#codemotion', 10) # ¿qué es 10? results =
search('#codemotion', min_retweets=10) results = search('#codemotion', limit=10)
• Argumentos con nombre – ☺ Código más legible –
☺ Parámetros documentados – ☹ Coste en rendimiento
Funciones Valores de retorno
def run_tests(): # … return (passed, failed, skipped)
☹ passed, failed, skipped = run_tests()
from collections import namedtuple TestResults = namedtuple('TestResults', [ 'passed', 'failed',
'skipped']) def run_tests(): # … return TestResults(passed, failed, skipped)
☺ results = run_tests() # results.passed # results.failed # results.skipped
Context Managers
• Setup y teardown – Operaciones de entrada/salida – Locks
– Contexto
☹ f = open('readme.md') try: content = f.read() finally: f.close()
☺ with open('readme.md') as f: content = f.read()
Excepciones
☹☹ import os try: os.remove('readme.md') except: pass
☹ import os try: os.remove('readme.md') except OSError: pass
☹ 3 import os try: os.remove('readme.md') except FileNotFoundError: pass
☺ >= 3.4 from contextlib import ignored with ignored(FileNotFoundError): os.remove('readme.md')
☺ < 3.4 from contextlib import contextmanager @contextmanager def ignored(*exceptions):
try: yield except exceptions: pass
Generator expressions
• Equivalentes a las comprensiones de listas pero perezosas –
Manipulación de secuencias en múltiples pasos – Secuencias como resultados intermedios
☹ uppercase_lines = [l.upper() for l in open('readme.md')] filtered_lines =
[l for l in uppercase_lines if l.startswith('#')] # ¿qué pasa si readme.md es un fichero ENORME? for l in filtered_lines: print(l)
☺ uppercase_lines = (l.upper() for l in open('readme.md')) filtered_lines =
(l for l in uppercase_lines if l.startswith('#')) # la iteración dirige la evaluación de las genexpressions for l in filtered_lines: print(l)
None
Escribid código bonito
¡Gracias!