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