Repository: pochmann/PyTricks Branch: master Commit: 46eb102f4ea9 Files: 45 Total size: 15.4 KB Directory structure: gitextract_1wg1_cmk/ ├── CONTRIBUTORS ├── PyTrickBase.txt ├── README.md ├── argumentunpacking.py ├── boolasint.py ├── cacheproperty.py ├── calculator.py ├── chainedcomparison.py ├── common_seq_method.py ├── concatenatestrings.py ├── conditionalassignment.py ├── conditionalfunctioncall.py ├── controlwhitespaces.py ├── copylist.py ├── dictionaryget.py ├── dictsortbyvalue.py ├── dictswapkeysvalues.py ├── exec.py ├── extendediterableunpacking.py ├── flattenlist.py ├── forelse.py ├── keydefaultdict.py ├── lightweightswitch.py ├── listtocommaseparated.py ├── loopoverlappingdicts.py ├── maxsplit.py ├── metatable.py ├── minmaxindex.py ├── namedformatting.py ├── nested_functions.py ├── objgetnamedattribute.py ├── rawinputintegers.py ├── removeduplicatefromlist.py ├── reverselist.py ├── setglobalvariables.py ├── setoperators.py ├── socketmsghandling.py ├── sortlistkeepindices.py ├── stepslice.py ├── transpose.py ├── tree.py ├── tryelse.py ├── unique_by_attr.py ├── valueswapping.py └── whileelse.py ================================================ FILE CONTENTS ================================================ ================================================ FILE: CONTRIBUTORS ================================================ - brennerm - agumonkey - obeleh - Prooffreader - cgopalan (cgopalan.github.io) - anabalica (ana-balica.github.io) - dharmit (github.com/dharmit) - shyboynccu (github.com/shyboynccu) - illuz - tutoringsteve - Kzinglzy - waveform80 (github.com/waveform80) - thatneat (github.com/thatneat) - bruno314 (github.com/bruno314) - rickhau - oztalha (github.com/oztalha) - nikhiln (github.com/nikhiln) - raulcd (github.com/raulcd) - betezed (github.com/betezed) - transcranial (github.com/transcranial) - st0le (http://st0le.github.io) - goutham2027 (github.com/goutham2027) - dcbaker - isayme - Skycker (github.com/Skycker) - vvscloud (github.com/vvscloud) - xamvolagis (github.com/xamvolagis) - richardasaurus (richard@richard.do) - lipinski (github.com/lipinski) ================================================ FILE: PyTrickBase.txt ================================================ #! /usr/bin/env python3 """""" ================================================ FILE: README.md ================================================ ## Intention Creating a knowledge base of unpopular Python built-in features to save a lot of unnecessary code. ## Contribute Feel free to use the PyTrickBase.txt as a starting point. 1. Pull request: Send a pull request with your PyTrick, containing example code and a documentation one-liner. Be sure to add yourself to the contributors. 2. Issue comment: Add your Python snippet and your documentation as a comment on Issue#1. I will take care of adding your PyTrick and you as a contributor. ### Requirements - only use the standard Python library - compared to the "general approach": - improve readability - improve performance - implement functionality in a shorter way ## Contact 1. message me at [@__brennerm](https://twitter.com/__brennerm) 2. send an email to xam.rennerb@gmail.com ================================================ FILE: argumentunpacking.py ================================================ #! /usr/bin/env python3 """simple tuple and dictionary unpacking""" def product(a, b): return a * b argument_tuple = (1, 1) argument_dict = {'a': 1, 'b': 1} print(product(*argument_tuple)) print(product(**argument_dict)) ================================================ FILE: boolasint.py ================================================ #! /usr/bin/env python3 """True and False can be used as integer values True -> 1 False -> 0 """ a = 5 print(isinstance(a, int) + (a <= 10)) print(["is odd", "is even"][a % 2 == 0]) ================================================ FILE: cacheproperty.py ================================================ class PropertyCache: """ a decorator to cache property """ def __init__(self, func): self.func = func def __get__(self, obj, cls): if not obj: return self value = self.func(obj) setattr(obj, self.func.__name__, value) return value class Foo: def __init__(self): self._property_to_be_cached = 'result' @PropertyCache def property_to_be_cached(self): print('compute') return self._property_to_be_cached test = Foo() print(test.property_to_be_cached) print(test.property_to_be_cached) ================================================ FILE: calculator.py ================================================ #!/usr/bin/env python3 """ This program lets you create a simple command line calculator without using the 'if..else' construct. It uses built-in 'operator' module to accomplish the same Created with help of an answer on stackoverflow. Don't have the exact link. """ import operator ops = { "+": operator.add, "-": operator.sub, "/": operator.truediv, "*": operator.mul } x = input("Enter an operator [OPTIONS: +, -, *, /]: ") y = int(input("Enter number: ")) z = int(input("Enter number: ")) print (ops[x](y, z)) ================================================ FILE: chainedcomparison.py ================================================ #! /usr/bin/env python3 """chained comparison with all kind of operators""" a = 10 print(1 < a < 50) print(10 == a < 20) ================================================ FILE: common_seq_method.py ================================================ #! /usr/bin/env python3 """Run common method of big sequence of objects""" import operator class Foo(): def bar(self, *args, **kwargs): print('method bar works') sequence = [Foo() for i in range(5)] # in python3 map returns iterator so we must ask python to process elements by list() # in python2 map(operator.methodcaller('bar'), sequence) works perfectly list(map(operator.methodcaller('bar'), sequence)) # there is another way more understandable [f.bar() for f in sequence] ================================================ FILE: concatenatestrings.py ================================================ #! /usr/bin/env python3 """Concatenate long strings elegantly across line breaks in code""" my_long_text = ("We are no longer the knights who say Ni! " "We are now the knights who say ekki-ekki-" "ekki-p'tang-zoom-boing-z'nourrwringmm!") ================================================ FILE: conditionalassignment.py ================================================ #! /usr/bin/env python3 """Python has two ways to do conditional assignments The first is a fairly standard teranary style; if else The second method takes advantage of the fact that python's or is lazy. When an assignment is made if the first value is falsy (None is falsy), then it will automatically return the second value, even if that value is falsy. """ b = True print(True if b else False) b = None or False print(b) ================================================ FILE: conditionalfunctioncall.py ================================================ #! /usr/bin/env python3 """calling different functions with same arguments based on condition""" def product(a, b): return a * b def subtract(a, b): return a - b b = True print((product if b else subtract)(1, 1)) ================================================ FILE: controlwhitespaces.py ================================================ #! /usr/bin/env python3 """control the whitespaces in string""" s = 'The Little Price' # justify string to be at least width wide # by adding whitespaces width = 20 s1 = s.ljust(width) s2 = s.rjust(width) s3 = s.center(width) print(s1) # 'The Little Price ' print(s2) # ' The Little Price' print(s3) # ' The Little Price ' # strip whitespaces in two sides of string print(s3.lstrip()) # 'The Little Price ' print(s3.rstrip()) # ' The Little Price' print(s3.strip()) # 'The Little Price' ================================================ FILE: copylist.py ================================================ #! /usr/bin/env python3 """a fast way to make a shallow copy of a list""" a = [1, 2, 3, 4, 5] print(a[:]) """using the list.copy() method (python3 only)""" a = [1, 2, 3, 4, 5] print(a.copy()) """copy nested lists using copy.deepcopy""" from copy import deepcopy l = [[1, 2], [3, 4]] l2 = deepcopy(l) print(l2) ================================================ FILE: dictionaryget.py ================================================ #! /usr/bin/env python3 """returning None or default value, when key is not in dict""" d = {'a': 1, 'b': 2} print(d.get('c', 3)) ================================================ FILE: dictsortbyvalue.py ================================================ #!/usr/bin/env python3 """ Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. """ d = {'apple': 10, 'orange': 20, 'banana': 5, 'rotten tomato': 1} print(sorted(d.items(), key=lambda x: x[1])) """ Sort using operator.itemgetter as the sort key instead of a lambda""" from operator import itemgetter print(sorted(d.items(), key=itemgetter(1))) """Sort dict keys by value""" print(sorted(d, key=d.get)) ================================================ FILE: dictswapkeysvalues.py ================================================ #! /usr/bin/env python3 """Swaps keys and values in a dict""" _dict = {"one": 1, "two": 2} # make sure all of dict's values are unique assert len(_dict) == len(set(_dict.values())) reversed_dict = {v: k for k, v in _dict.items()} ================================================ FILE: exec.py ================================================ #! /usr/bin/env python3 """exec can be used to execute Python code during runtime variables can be handed over as a dict """ exec("print('Hello ' + s)", {'s': 'World'}) ================================================ FILE: extendediterableunpacking.py ================================================ #! /usr/bin/env python3 """allows collecting not explicitly assigned values into a placeholder variable""" a, *b, c = range(10) print(a, b, c) """advanced example""" [(c, *d, [*e]), f, *g] = [[1, 2, 3, 4, [5, 5, 5]], 6, 7, 8] print(c, d, e, f, g) ================================================ FILE: flattenlist.py ================================================ #! /usr/bin/env python3 """ Deep flattens a nested list Examples: >>> list(flatten_list([1, 2, [3, 4], [5, 6, [7]]])) [1, 2, 3, 4, 5, 6, 7] >>> list(flatten_list(['apple', 'banana', ['orange', 'lemon']])) ['apple', 'banana', 'orange', 'lemon'] """ def flatten_list(L): for item in L: if isinstance(item, list): yield from flatten_list(item) else: yield item # In Python 2 from compiler.ast import flatten flatten(L) # Flatten list of lists a = [[1, 2], [3, 4]] # Solutions: print([x for _list in a for x in _list]) import itertools print(list(itertools.chain(*a))) print(list(itertools.chain.from_iterable(a))) # In Python 2 print(reduce(lambda x, y: x+y, a)) print(sum(a, [])) ================================================ FILE: forelse.py ================================================ #! /usr/bin/env python3 """else gets called when for loop does not reach break statement""" a = [1, 2, 3, 4, 5] for el in a: if el == 0: break else: print('did not break out of for loop') ================================================ FILE: keydefaultdict.py ================================================ """ keydefaultdict with where the function recieves the key. """ from collections import defaultdict class keydefaultdict(defaultdict): def __missing__(self, key): if self.default_factory is None: raise KeyError(key) else: ret = self[key] = self.default_factory(key) return ret def pow2(n): return 1 << n d = keydefaultdict(pow2) print(d[1]) print(d[3]) print(d[10]) print(d) ================================================ FILE: lightweightswitch.py ================================================ #! /usr/bin/env python3 """lightweight switch statement""" a = { True: 1, False: -1, None: 0 } print(a.get(False, 0)) """works with functions as well""" def add(a, b): return a + b def subtract(a, b): return a - b b = { '+': add, '-': subtract } print(b['+'](1, 1)) ================================================ FILE: listtocommaseparated.py ================================================ #! /usr/bin/env python3 """converts list to comma separated string""" items = ['foo', 'bar', 'xyz'] print (','.join(items)) """list of numbers to comma separated""" numbers = [2, 3, 5, 10] print (','.join(map(str, numbers))) """list of mix data""" data = [2, 'hello', 3, 3.4] print (','.join(map(str, data))) ================================================ FILE: loopoverlappingdicts.py ================================================ #! /usr/bin/env python3 """loop over dicts that share (some) keys in Python2""" dctA = {'a': 1, 'b': 2, 'c': 3} dctB = {'b': 4, 'c': 3, 'd': 6} for ky in set(dctA) & set(dctB): print(ky) """loop over dicts that share (some) keys in Python3""" for ky in dctA.keys() & dctB.keys(): print(ky) """loop over dicts that share (some) keys and values in Python3""" for item in dctA.items() & dctB.items(): print(item) ================================================ FILE: maxsplit.py ================================================ #! /usr/bin/env python3 """split a string max times""" string = "a_b_c" print(string.split("_", 1)) """use maxsplit with arbitrary whitespace""" s = "foo bar foobar foo" print(s.split(None, 2)) ================================================ FILE: metatable.py ================================================ """ metatable with where the function recieves the dictionary and key. """ from collections import defaultdict class metatable(defaultdict): def __missing__(self, key): if self.default_factory is None: raise KeyError(key) else: ret = self[key] = self.default_factory(self, key) return ret def fib(d, n): if n == 0 or n == 1: return n return d[n - 1] + d[n - 2] d = metatable(fib) print(d[1]) print(d[3]) print(d[10]) print(d) ================================================ FILE: minmaxindex.py ================================================ """ Find Index of Min/Max Element. """ lst = [40, 10, 20, 30] def minIndex(lst): return min(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 def maxIndex(lst): return max(range(len(lst)), key=lst.__getitem__) # use xrange if < 2.7 print(minIndex(lst)) print(maxIndex(lst)) ================================================ FILE: namedformatting.py ================================================ #! /usr/bin/env python3 """easy string formatting using dicts""" d = {'name': 'Jeff', 'age': 24} print("My name is %(name)s and I'm %(age)i years old." % d) """for .format, use this method""" d = {'name': 'Jeff', 'age': 24} print("My name is {name} and I'm {age} years old.".format(**d)) """dict string formatting""" c = {'email': 'jeff@usr.com', 'phone': '919-123-4567'} print('My name is {0[name]}, my email is {1[email]} and my phone number is {1[phone]}'.format(d, c)) ================================================ FILE: nested_functions.py ================================================ #!/usr/bin/env python3 """nested functions""" def addBy(val): def func(inc): return val + inc return func addFive = addBy(5) print(addFive(4)) addThree = addBy(3) print(addThree(7)) ================================================ FILE: objgetnamedattribute.py ================================================ #! /usr/bin/env python3 """ Return the value of the named attribute of an object """ class obj(): attr = 1 foo = "attr" print(getattr(obj, foo)) ================================================ FILE: rawinputintegers.py ================================================ #! /usr/bin/env python3 """ Convert raw string integer inputs to integers """ str_input = "1 2 3 4 5 6" print("### Input ###") print(str_input) int_input = map(int, str_input.split()) print("### Output ###") print(list(int_input)) ================================================ FILE: removeduplicatefromlist.py ================================================ #! /usr/bin/env python3 """remove duplicate items from list. note: does not preserve the original list order""" items = [2, 2, 3, 3, 1] newitems2 = list(set(items)) print(newitems2) """remove dups and keep order""" from collections import OrderedDict items = ["foo", "bar", "bar", "foo"] print(list(OrderedDict.fromkeys(items).keys())) ================================================ FILE: reverselist.py ================================================ #! /usr/bin/env python3 """reversing list with special case of slice step param""" a = [5, 4, 3, 2, 1] print(a[::-1]) """iterating over list contents in reverse efficiently.""" for ele in reversed(a): print(ele) ================================================ FILE: setglobalvariables.py ================================================ #! /usr/bin/env python3 """set global variables from dict""" d = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]} globals().update(d) print(a, b, c) ================================================ FILE: setoperators.py ================================================ #! /usr/bin/env python3 """Python provides usual set operator""" a = set(['a', 'b', 'c', 'd']) b = set(['c', 'd', 'e', 'f']) c = set(['a', 'c']) # Intersection print(a & b) # Subset print(c < a) # Difference print(a - b) # Symmetric Difference print(a ^ b) # Union print(a | b) """using methods instead of operators which take any iterable as a second arg""" a = {'a', 'b', 'c', 'd'} b = {'c', 'd', 'e', 'f'} c = {'a', 'c'} print(a.intersection(["b"])) print(a.difference(["foo"])) print(a.symmetric_difference(["a", "b", "e"])) print(a.issuperset(["b", "c"])) print(a.issubset(["a", "b", "c", "d", "e", "f"])) print(a.isdisjoint(["y", 'z'])) print(a.union(["foo", "bar"])) a.intersection_update(["a", "c", "z"]) print(a) ================================================ FILE: socketmsghandling.py ================================================ import socket import functools s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) conn = s.connect(('localhost', 80)) msgs = [] # normal way # while True: # msg = coon.recv(1024) # if recv: # msgs.append(msg) # else: # when no msg come, break # break # hack way with iter and functools.partial # this circle will auto break when msg is empty '' for msg in iter(functools.partial(conn.recv, 1024), b''): msgs.append(msg) ================================================ FILE: sortlistkeepindices.py ================================================ #! /usr/bin/env python3 """Sort a list and store previous indices of values""" # enumerate is a great but little-known tool for writing nice code l = [4, 2, 3, 5, 1] print("original list: ", l) values, indices = zip(*sorted((a, b) for (b, a) in enumerate(l))) # now values contains the sorted list and indices contains # the indices of the corresponding value in the original list print("sorted list: ", values) print("original indices: ", indices) # note that this returns tuples, but if necessary they can # be converted to lists using list() ================================================ FILE: stepslice.py ================================================ #! /usr/bin/env python3 """stepwise slicing of arrays""" a = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] print(a[::3]) ================================================ FILE: transpose.py ================================================ #! /usr/bin/env python3 """transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]""" original = [['a', 'b'], ['c', 'd'], ['e', 'f']] transposed = zip(*original) print(list(transposed)) ================================================ FILE: tree.py ================================================ #! /usr/bin/env python3 """ See description here https://gist.github.com/hrldcpr/2012250 """ from collections import defaultdict tree = lambda: defaultdict(tree) users = tree() users['harold']['username'] = 'chopper' users['matt']['password'] = 'hunter2' ================================================ FILE: tryelse.py ================================================ """ You can have an 'else' clause with try/except. It gets excecuted if no exception is raised. This allows you to put less happy-path code in the 'try' block so you can be more sure of where a caught exception came from.""" try: 1 + 1 except TypeError: print("Oh no! An exception was raised.") else: print("Oh good, no exceptions were raised.") ================================================ FILE: unique_by_attr.py ================================================ #! /usr/bin/env python3 """ If we have some sequence of objects and want to remove items with the same attribute value Python creates a dict, where keys are value if attribute (bar in our case), values are object of the sequence. After that the dict is transformed back to list Note: in result we save the last from repeating elements (item2 in our case)! """ class Foo: def __init__(self, value): self.bar = value item1 = Foo(15) item2 = Foo(15) item3 = Foo(5) lst = [item1, item2, item3] unique_lst = list({getattr(obj, 'bar'): obj for obj in lst}.values()) print(unique_lst) # [item2, item3] ================================================ FILE: valueswapping.py ================================================ #! /usr/bin/env python3 """pythonic way of value swapping""" a, b = 5, 10 print(a, b) a, b = b, a print(a, b) ================================================ FILE: whileelse.py ================================================ """ You can have an else clause with a while. Works like for-else. When break is encountered, it exits the loop without executing else. """ i = 5 while i > 1: print("Whil-ing away!") i -= 1 if i == 3: break else: print("Finished up!")