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
Alejandro Gómez
October 20, 2013
Programming
2
150
Python Idiomático
Alejandro Gómez
October 20, 2013
Tweet
Share
Other Decks in Programming
See All in Programming
TypeScript Graph でコードレビューの心理的障壁を乗り越える
ysk8hori
3
1.2k
カンファレンスの「アレ」Webでなんとかしませんか? / Conference “thing” Why don't you do something about it on the Web?
dero1to
1
110
OnlineTestConf: Test Automation Friend or Foe
maaretp
0
120
EMになってからチームの成果を最大化するために取り組んだこと/ Maximize team performance as EM
nashiusagi
0
100
レガシーシステムにどう立ち向かうか 複雑さと理想と現実/vs-legacy
suzukihoge
15
2.3k
イマのCSSでできる インタラクション最前線 + CSS最新情報
clockmaker
4
2.5k
Micro Frontends Unmasked Opportunities, Challenges, Alternatives
manfredsteyer
PRO
0
110
cmp.Or に感動した
otakakot
3
250
みんなでプロポーザルを書いてみた
yuriko1211
0
280
Duckdb-Wasmでローカルダッシュボードを作ってみた
nkforwork
0
130
광고 소재 심사 과정에 AI를 도입하여 광고 서비스 생산성 향상시키기
kakao
PRO
0
170
ふかぼれ!CSSセレクターモジュール / Fukabore! CSS Selectors Module
petamoriken
0
150
Featured
See All Featured
The Illustrated Children's Guide to Kubernetes
chrisshort
48
48k
Measuring & Analyzing Core Web Vitals
bluesmoon
4
140
Java REST API Framework Comparison - PWX 2021
mraible
PRO
28
8.2k
The Straight Up "How To Draw Better" Workshop
denniskardys
232
140k
Fight the Zombie Pattern Library - RWD Summit 2016
marcelosomers
232
17k
Become a Pro
speakerdeck
PRO
25
5k
Gamification - CAS2011
davidbonilla
80
5k
Principles of Awesome APIs and How to Build Them.
keavy
126
17k
Helping Users Find Their Own Way: Creating Modern Search Experiences
danielanewman
29
2.3k
What’s in a name? Adding method to the madness
productmarketing
PRO
22
3.1k
ReactJS: Keep Simple. Everything can be a component!
pedronauck
665
120k
Code Reviewing Like a Champion
maltzj
520
39k
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!