Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Beautiful python - PyLadies

Beautiful python - PyLadies

En esta charla veremos con detalle algunas de las construcciones más pythonicas y las posibilidades de expresar de forma clara, concisa y elegante cosas que en otros lenguajes nos obligarían a dar muchos rodeos.
A veces es fácil olvidar algunos recursos como que una función puede devolver varios valores, cómo manipular listas y diccionarios de forma sencilla, contextos, generadores... En esta charla veremos de forma entretenida y práctica cómo mejorar nuestro nivel de Python "nativo".

Alicia Pérez Jiménez

October 19, 2017
Tweet

More Decks by Alicia Pérez Jiménez

Other Decks in Technology

Transcript

  1. # Cadenas muy largas my_very_big_string = 'For a long time

    I used to go to bed early. ' + \ 'Sometimes, when I had put out my candle, my eyes would close ' + \ 'so quickly that I had not even time to say Im going to sleep.' my_very_big_string = '''For a long time I used to go to bed early. Sometimes, when I had put out my candle, my eyes would close so quickly that I had not even time to say Im going to sleep.''' my_very_big_string = ('For a long time I used to go to bed early. ' 'Sometimes, when I had put out my candle, my eyes would close ' 'so quickly that I had not even time to say Im going to sleep.')
  2. if stylesage.find('Fashion') != -1: pass # Comprobar si una cadena

    contiene otra stylesage = 'Fashion meets Big Data' if 'Fashion' in stylesage: pass
  3. >>> name = 'Alicia' >>> cats = 2 >>> print('My

    name is ' + name + ' and I have ' + str(cats) + ' cats') # Usa String Formatting!!
  4. #1 – “Old Style” >>> name = 'Bob' >>> 'Hello,

    %s' % name 'Hello, Bob' # String Formatting #2 – “New Style” String Formatting >>> name = 'Bob' >>> 'Hello, {}'.format(name) 'Hello, Bob' #3 – Literal String Interpolation # (Python 3.6+) >>> name = 'Bob' >>> f'Hello, {name}' 'Hello, Bob' #4 – Template Strings >>> from string import Template >>> t = Template('Hello, $name!') >>> t.substitute(name='Bob') 'Hello, Bob!'
  5. >>> if x >= start and x <= end: >>>

    pass >>> if len(items) != 0: >>> pass >>> if lang == 'Spanish': ... welcome = 'Bienvenido' ... else: ... welcome = 'Welcome' >>> if start <= x <= end: >>> pass >>> if items: >>> pass >>> welcome = 'Bienvenido' \ ... if lang == 'Spanish' else 'Welcome'
  6. Truth Value Testing Los siguientes valores serán evaluados como False

    en una comparación: • None • False • Cero en cualquier tipo numérico, por ejemplo: 0, 0L, 0.0, 0j • Cualquier secuencia vacía, por ejemplo: '', (), [] • Los diccionarios vacíos: {} • Las instancias de cualquier clase, si esta define los métodos __nonzero__() o __len__(), cuando estos métodos devuelven cero o False En cualquier otro caso, serán evaluados como True
  7. >>> values = [True, True, False, False] >>> i =

    0 >>> flag = False >>> while not flag and i < len(values): ... flag = values[i] ... i += 1 >>> flag False >>> any(values) True # ¿algún True en la lista? >>> all(values) False
  8. >>> values = range(10) # [0, 1, 2, 3, 4,

    5, 6, 7, 8, 9] >>> i = 0 >>> flag = False >>> while not flag and i < len(values): ... flag = (values[i] == 0) ... i += 1 >>> flag True >>> any(values) True # ¿algún 0 en la lista? >>> all(values) False
  9. >>> b, a = a, b >>> temp = a

    >>> a = b >>> b = temp >>> l = ['David', 'Pythonista', '555-55-55'] >>> name = l[0] >>> title = l[1] >>> phone = l[2] >>> name, title, phone = l >>> name, _, phone = l
  10. # Crear una tupla >>> arr = 'one', 'two', 'three'

    >>> arr[0] 'One' # Son immutables: >>> arr[1] = 'hello' TypeError: "'tuple' object does not support item assignment" >>> del arr[1] TypeError: "'tuple' object doesn't support item deletion" # Soportan múltiples # tipos de datos: >>> arr + (23,) ('one', 'two', 'three', 23)
  11. # namedtuples >>> from collections \ ... import namedtuple >>>

    Car = namedtuple('Car', \ ... 'color mileage automatic') >>> car1 = Car('red', 3812.4, True) # Acceder a los campos: >>> car1.color 'red' >>> car1.mileage 3812.4 >>> car1.automatic True # Los campos son inmutables: >>> car1.mileage = 12 AttributeError: "can't set attribute"
  12. # Crear una lista >>> arr = ['one', 'two', 'three']

    >>> arr[0] 'One' # Son mutables: >>> arr[1] = 'hello' >>> arr ['one', 'hello', 'three'] >>> del arr[1] >>> arr ['one', 'three'] # Soportan múltiples tipos: >>> arr.append(23) >>> arr ['one', 'three', 23]
  13. # array slicing a = [0, 1, 2, 3, 4,

    5, 6, 7, 8, 9, 10] >>> a[-1] 10 >>> a[2:8] [2, 3, 4, 5, 6, 7] >>> a[:5] [0, 1, 2, 3, 4] >>> a[5:] [5, 6, 7, 8, 9, 10] >>> a[2:8:2] [2, 4, 6] >>> a[::2] [0, 2, 4, 6, 8, 10] >>> a = [1, 2, 3, 4, 5] >>> a[2:4] = [0, 0, 0] >>> a [1, 2, 0, 0, 0, 5]
  14. >>> A = {1, 2, 3, 3} >>> B =

    {3, 4, 5, 6, 7} >>> A set([1, 2, 3]) >>> B set([3, 4, 5, 6, 7]) >>> A | B set([1, 2, 3, 4, 5, 6, 7]) >>> A & B set([3]) >>> A - B set([1, 2]) >>> A ^ B set([1, 2, 4, 5, 6, 7])
  15. >>> A Counter({2: 2, 1: 1}) >>> B Counter({2: 2,

    3: 1}) >>> C.most_common() [(3, 4), (1, 2), (2, 2), (4, 1), (5, 1), (6, 1), (7, 1)] >>> C.most_common(1) [(3, 4)] >>> C.most_common(3) [(3, 4), (1, 2), (2, 2)] >>> A = collections.Counter([1, 2, 2]) >>> B = collections.Counter([2, 2, 3]) >>> C = collections.Counter([1, 1, 2, 2, 3, 3, 3, 3, 4, 5, 6, 7]) >>> A | B Counter({2: 2, 1: 1, 3: 1}) >>> A & B Counter({2: 2}) >>> A + B Counter({2: 4, 1: 1, 3: 1})
  16. >>> a = ['Hello', 'world', '!'] >>> for i, x

    in enumerate(a): ... print '{}: {}'.format(i, x) >>> a = ['Hello', 'world', '!'] >>> i = 0 >>> for x in a: ... print '{}: {}'.format(i, x) ... i += 1 # Imprimir los elementos de una lista y su índice
  17. >>> squares = [x * x for x in range(10)]

    >>> even_squares = [] >>> for x in range(10): ... even_squares.append(x * x) >>> even_squares = [] >>> for x in range(10): ... if x % 2 == 0: ... even_squares.append(x * x) >>> even_squares = [x * x for x in range(10) \ ... if x % 2 == 0] # Obtener todos los cuadrados de los números del 0 al 9 # Obtener todos los cuadrados de los números pares del 0 al 9
  18. >>> zip(names, surnames) [('John', 'Cleese'), ('Eric', 'Idle'), ('Terry', 'Gilliam')] >>>

    names = ['John', 'Eric', 'Terry'] >>> surnames = ['Cleese', 'Idle', 'Gilliam'] >>> people = [] >>> for i in range(len(names)): ... people.append((names[i], surnames[i])) >>> print(people) [('John', 'Cleese'), ('Eric', 'Idle'), ('Terry', 'Gilliam')] # Obtener en una sola lista los pares nombre-apellido
  19. >>> squares = (i*i for i in xrange(1000000)) >>> next(squares)

    0 >>> next(squares) 1 >>> next(squares) 4 >>> next(squares) 9 >>> next(squares) 16 >>> from collections import deque >>> q = deque(squares) >>> q.pop() 999998000001 >>> q.pop() 999996000004 >>> q.popleft() 0 >>> q.popleft() 1 >>> squares = [i*i for i in range(1000000)]
  20. # Add to the right >>> d = collections.deque() >>>

    d.extend([0, 1, 2, 3, 4]) deque([0, 1, 2, 3, 4]) >>> d.append(5) deque([0, 1, 2, 3, 4, 5]) # Add to the left >>> d = collections.deque() >>> d.extendleft([0, 1, 2, 3, 4]) deque([4, 3, 2, 1, 0]) >>> d.appendleft(5) deque([5, 4, 3, 2, 1, 0])
  21. >>> last_three = collections.deque(maxlen=3) >>> for i in xrange(5): ...

    last_three.append(i) ... print ', '.join( ... str(x) for x in last_three) 0 0, 1 0, 1, 2 1, 2, 3 2, 3, 4
  22. >>> name_for_userid = { ... 382: 'Alice', ... 950: 'Bob',

    ... 590: 'Dilbert', ... } >>> def greeting(userid): ... if userid in name_for_userid: ... return 'Hi %s!' % name_for_userid[userid] ... else: ... return 'Hi there!'
  23. >>> def greeting(userid): ... try: ... return 'Hi %s!' %

    name_for_userid[userid] ... except KeyError: ... return 'Hi there' >>> def greeting(userid): ... return 'Hi %s!' % user_dict.get(userid, 'there')
  24. >>> visits = { ... 'Alice': 0, ... 'Bob': 0,

    ... 'Dilbert': 0, ... } >>> def add_visit(user): ... if user not in visits: ... visits[user] = 0 ... visits[user] += 1 >>> def add_visit(user): ... visits.setdefault(user, 0) ... visits[user] += 1 >>> def add_visit(user): ... visits[user] = visits.get(user, 0) + 1 >>> visits = defaultdict(int) >>> def add_visit(user): ... visits[user] += 1
  25. >>> m = {x: x ** 2 for x in

    range(5)} >>> m {0: 0, 1: 1, 2: 4, 3: 9, 4: 16} >>> m = {x: 'A' + str(x) for x in range(5)} >>> m {0: 'A0', 1: 'A1', 2: 'A2', 3: 'A3', 4: 'A4', 5} >>> # Invertir las clave-valor >>> m = {'a': 1, 'b': 2, 'c': 3, 'd': 4} >>> {v: k for k, v in m.items()} {1: 'a', 2: 'b', 3: 'c', 4: 'd'}
  26. # * args >>> def test_var_args(f_arg, *argv): ... print "first

    normal arg:", f_arg ... for arg in argv: ... print "another arg through *argv :", arg >>> test_var_args() Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: test_var_args() takes at least 1 argument (0 given) >>> test_var_args('yasoob', 'python', 'eggs', 'test') 'first normal arg: yasoob' 'another arg through *argv : python' 'another arg through *argv : eggs' 'another arg through *argv : test'
  27. # ** kargs >>> def greet_me(**kwargs): ... for key, value

    in kwargs.iteritems(): ... print "%s == %s" %(key,value) >>> greet_me(name="yasoob") 'name == yasoob' >>> kwargs = {"arg3": 3, "arg2": "two", "arg1":5} >>> greet_me(**kwargs) 'arg1 == 5' 'arg2 == two' 'arg3 == 3'
  28. >>> def apply_discount(product, discount): ... price = int(product['price'] * (1.0

    - discount)) ... assert 0 <= price <= product['price'] ... return price >>> shoes = {'name': 'Fancy Shoes', 'price': 14900} >>> apply_discount(shoes, 0.25) 11175 >>> apply_discount(shoes, 2.0) Traceback (most recent call last): File "<input>", line 1, in <module> apply_discount(prod, 2.0) File "<input>", line 4, in apply_discount assert 0 <= price <= product['price'] AssertionError
  29. # internamente un assert es... >>> if __debug__: ... if

    not expression1: ... raise AssertionError(expression2) # por eso nunca hay que hacer... >>> def delete_product(prod_id, user): >>> assert user.is_admin(), 'Comprueba si es administrador' >>> assert store.has_product(prod_id), 'Comprueba si existe' >>> store.get_product(prod_id).delete()
  30. // WARNING!! Código Java en una charla Python!! void muestraContenido(String

    archivo) throws FileNotFoundException, IOException { String cadena; FileReader f = new FileReader(archivo); BufferedReader b = new BufferedReader(f); while((cadena = b.readLine())!=null) { System.out.println(cadena); } b.close(); }
  31. class File(): def __init__(self, filename, mode): self.filename = filename self.mode

    = mode def __enter__(self): self.open_file = open(self.filename, self.mode) return self.open_file def __exit__(self, *args): self.open_file.close()
  32. Referencias Python Tricks: The Book A Buffet of Awesome Python

    Features 30 Python Language Features and Tricks You May Not Know About PYTHON TIPS web