119 views
# NO PYTHON FIRA CODE RETINA # huevos de pascua ```python import this # see this.py viola el zen de python import antigravity import __hello__ from __future__ import braces ``` # place for a meetup ```python from antigravity import geohash # Your location, a date and that date's (or most recent) DJIA opening. geohash(37.421542, -122.085589, b'2005-05-26-10458.68') 37.857713 -122.544543 # This can generate a GPS coordinate in a region which is 1 longitude long and 1 latitude wide based on your location. ``` # python ellipsis (arrays, fastapi, functions) ```python def pending_func(): ... def empy_func(): pass def not_implemented_func(): raise NotImplementedError() ``` # Restrict inequality ```python from __future__ import barry_as_FLUFL 1 <> 2 True 1 != 2 File "<stdin>", line 1 1 != 2 ^ SyntaxError: invalid syntax ``` # Patch ```python from unittest.mock import patch ... class WhoTweetedTestCase(unittest.TestCase): @patch.object(tweepy.API, 'get_status', return_value=get_tweet('AU')) def test_julian(self, mock_method): ... @patch.object(tweepy.API, 'get_status', return_value=get_tweet('ES')) def test_bob(self, mock_method): ... ``` # Closures ```python def function_outside(): msg = 'Hi' def function_inside(): nonlocal msg msg = 'Hello' print (msg) function_inside() print (msg) def fib(): n1 = 0 n2 = 1 def get_next_number(): nonlocal n1, n2 n1, n2 = n2, n1 + n2 return n2 return get_next_number ``` # Integer Caching ```python -5...256 ``` # InPynite ```python infinity = float('infinity') hash(infinity) 314159 hash(float('-inf')) -314159 ``` # LRU CACHE ```python from functools import lru_cache @lru_cache(maxsize=32) def fib(n): if n < 2: return n return fib(n-1) + fib(n-2) > print([fib(n) for n in range(10)]) > Output: [0, 1, 1, 2, 3, 5, 8, 13, 21, 34] ``` # FUNCTOOLS ```python from functools import partial print_no_newline = partial(print, end=', ') ``` # Coroutines with (yield) ```python def grep(pattern): print("Searching for", pattern) while True: line = (yield) if pattern in line: print(line) search = grep('coroutine') next(search) > Output: Searching for coroutine > search.send("I love you") > search.send("Don't you love me?") > search.send("I love coroutines instead!") > Output: I love coroutines instead! ``` # Flattening a list ```python a_list = [[1, 2], [3, 4], [5, 6]] print(list(itertools.chain.from_iterable(a_list))) > Output: [1, 2, 3, 4, 5, 6] ``` # unzip ```python full_name_list = [('Joe', 'Schmoe', 23), ('Earnst', 'Ehlmann', 65), ('Thomas', 'Fischer', 11), ('Martin', 'Walter', 36), ('Charles', 'Rogan', 83)] first_name, last_name, age = list(zip(*full_name_list)) print(f"first name: {first_name}\nlast name: {last_name} \nage: {age}") > Output > first name: ('Joe', 'Earnst', 'Thomas', 'Martin', 'Charles') > last name: ('Schmoe', 'Ehlmann', 'Fischer', 'Walter', 'Rogan') > age: (23, 65, 11, 36, 83) ``` # Defaultdict ```python from collections import defaultdict tree = lambda: defaultdict(tree) some_dict = tree() some_dict['colours']['favourite'] = "yellow" # Don't fail ``` # Naming Slices ```python # Naming slices (slice(start, end, step)) a = [0, 1, 2, 3, 4, 5] LASTTHREE = slice(-3, None) LASTTHREE > slice(-3, None, None) a[LASTTHREE] > [3, 4, 5] ``` # Contextlib Supress ```python from contextlib import suppress with contextlib.suppress(ZeroDivisionError): 10/0 > No exception raised ``` # Pathlib ```python from pathlib import Path data_folder = Path("source_data/text_files/") # Path calculation and metadata file_to_open = data_folder / "raw_data.txt" file_to_open.name "raw_data.txt" file_to_open.suffix "txt" file_to_open.stem "raw_data" # Files functions f = open(file_to_open) f.read() # content of the file file_to_open.exists() True ``` # try else finally ```python try: foo() except Exception: print("Exception occured") else: print("Exception didnt occur") finally: print("Always gets here") ``` # StrictVersion ```python from distutils.version import StrictVersion StrictVersion('0.12.1') < StrictVersion('1.0.2') True ``` # Functions in dicts ```python >>> func_dict = { 'sum': lambda x, y: x + y, 'subtract': lambda x, y: x - y } >>> func_dict['sum'](9,3) 12 >>> func_dict['subtract'](9,3) 6 ``` # other ```python from textwrap import dedent from collections import deque from dateutil import parse, relativedelta from itertools import cycle, chain, groupby, takewhile, dropwhile, product, permutations, combinations itertools.chain.from_iterable(<iterable>) str.split(<parameter>) round(<negative values>) enumerate(<iterable>) 1 < n < 20 # multiples predicados (uso o no) a, b, c = 1, 2, 3 # empaquetado y desempaquetado (opiniones) ```