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
2
160
Python Idiomático
Alejandro Gómez
October 20, 2013
Tweet
Share
Other Decks in Programming
See All in Programming
ふつうの Rubyist、ちいさなデバイス、大きな一年
bash0c7
0
950
Windows on Ryzen and I
seosoft
0
290
「抽象に依存せよ」が分からなかった新卒1年目の私が Goのインターフェースと和解するまで
kurogenki
0
120
API Platformを活用したPHPによる本格的なWeb API開発 / api-platform-book-intro
ttskch
1
140
[SF Ruby Feb'26] The Silicon Heel
palkan
0
100
OTP を自動で入力する裏技
megabitsenmzq
0
110
受け入れテスト駆動開発(ATDD)×AI駆動開発 AI時代のATDDの取り組み方を考える
kztakasaki
2
580
What Spring Developers Should Know About Jakarta EE
ivargrimstad
0
310
new(1.26) ← これすき / kamakura.go #8
utgwkk
0
2.3k
オブザーバビリティ駆動開発って実際どうなの?
yohfee
3
840
Agentic AI: Evolution oder Revolution
mobilelarson
PRO
0
180
New in Go 1.26 Implementing go fix in product development
sunecosuri
0
440
Featured
See All Featured
[RailsConf 2023] Rails as a piece of cake
palkan
59
6.4k
The Cost Of JavaScript in 2023
addyosmani
55
9.8k
How to Grow Your eCommerce with AI & Automation
katarinadahlin
PRO
1
140
SEO for Brand Visibility & Recognition
aleyda
0
4.4k
Google's AI Overviews - The New Search
badams
0
930
Primal Persuasion: How to Engage the Brain for Learning That Lasts
tmiket
0
290
How Software Deployment tools have changed in the past 20 years
geshan
0
33k
Paper Plane (Part 1)
katiecoart
PRO
0
5.6k
Design and Strategy: How to Deal with People Who Don’t "Get" Design
morganepeng
133
19k
Groundhog Day: Seeking Process in Gaming for Health
codingconduct
0
120
The Art of Delivering Value - GDevCon NA Keynote
reverentgeek
16
1.9k
世界の人気アプリ100個を分析して見えたペイウォール設計の心得
akihiro_kokubo
PRO
67
37k
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!