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 <xam.rennerb@gmail.com>
- 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
"""<documentation>"""
<example code>
================================================
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;
<value if true> if <conditional> else <value if false>
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!")
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
SYMBOL INDEX (26 symbols across 12 files)
FILE: argumentunpacking.py
function product (line 3) | def product(a, b):
FILE: cacheproperty.py
class PropertyCache (line 1) | class PropertyCache:
method __init__ (line 5) | def __init__(self, func):
method __get__ (line 8) | def __get__(self, obj, cls):
class Foo (line 16) | class Foo:
method __init__ (line 17) | def __init__(self):
method property_to_be_cached (line 21) | def property_to_be_cached(self):
FILE: common_seq_method.py
class Foo (line 6) | class Foo():
method bar (line 7) | def bar(self, *args, **kwargs):
FILE: conditionalfunctioncall.py
function product (line 3) | def product(a, b):
function subtract (line 6) | def subtract(a, b):
FILE: flattenlist.py
function flatten_list (line 13) | def flatten_list(L):
FILE: keydefaultdict.py
class keydefaultdict (line 7) | class keydefaultdict(defaultdict):
method __missing__ (line 8) | def __missing__(self, key):
function pow2 (line 16) | def pow2(n):
FILE: lightweightswitch.py
function add (line 11) | def add(a, b):
function subtract (line 14) | def subtract(a, b):
FILE: metatable.py
class metatable (line 7) | class metatable(defaultdict):
method __missing__ (line 9) | def __missing__(self, key):
function fib (line 17) | def fib(d, n):
FILE: minmaxindex.py
function minIndex (line 8) | def minIndex(lst):
function maxIndex (line 12) | def maxIndex(lst):
FILE: nested_functions.py
function addBy (line 3) | def addBy(val):
FILE: objgetnamedattribute.py
class obj (line 3) | class obj():
FILE: unique_by_attr.py
class Foo (line 11) | class Foo:
method __init__ (line 12) | def __init__(self, value):
Condensed preview — 45 files, each showing path, character count, and a content snippet. Download the .json file or copy for the full structured content (19K chars).
[
{
"path": "CONTRIBUTORS",
"chars": 779,
"preview": "- brennerm <xam.rennerb@gmail.com>\n- agumonkey\n- obeleh\n- Prooffreader\n- cgopalan (cgopalan.github.io)\n- anabalica (ana-"
},
{
"path": "PyTrickBase.txt",
"chars": 62,
"preview": "#! /usr/bin/env python3\n\"\"\"<documentation>\"\"\"\n\n<example code>\n"
},
{
"path": "README.md",
"chars": 815,
"preview": "## Intention\nCreating a knowledge base of unpopular Python built-in features to save a lot of unnecessary code.\n\n## Cont"
},
{
"path": "argumentunpacking.py",
"chars": 227,
"preview": "#! /usr/bin/env python3\n\"\"\"simple tuple and dictionary unpacking\"\"\"\ndef product(a, b):\n return a * b\n\nargument_tuple "
},
{
"path": "boolasint.py",
"chars": 181,
"preview": "#! /usr/bin/env python3\n\"\"\"True and False can be used as integer values\nTrue -> 1\nFalse -> 0\n\"\"\"\na = 5\nprint(isinstance("
},
{
"path": "cacheproperty.py",
"chars": 606,
"preview": "class PropertyCache:\n \"\"\" a decorator to cache property\n \"\"\"\n\n def __init__(self, func):\n self.func = fu"
},
{
"path": "calculator.py",
"chars": 534,
"preview": "#!/usr/bin/env python3\n\"\"\"\nThis program lets you create a simple command line calculator without using\nthe 'if..else' co"
},
{
"path": "chainedcomparison.py",
"chars": 121,
"preview": "#! /usr/bin/env python3\n\"\"\"chained comparison with all kind of operators\"\"\"\na = 10\nprint(1 < a < 50)\nprint(10 == a < 20)"
},
{
"path": "common_seq_method.py",
"chars": 497,
"preview": "#! /usr/bin/env python3\n\"\"\"Run common method of big sequence of objects\"\"\"\nimport operator\n\n\nclass Foo():\n def bar(se"
},
{
"path": "concatenatestrings.py",
"chars": 272,
"preview": "#! /usr/bin/env python3\n\"\"\"Concatenate long strings elegantly \nacross line breaks in code\"\"\"\n\nmy_long_text = (\"We are no"
},
{
"path": "conditionalassignment.py",
"chars": 476,
"preview": "#! /usr/bin/env python3\n\"\"\"Python has two ways to do conditional assignments\n\nThe first is a fairly standard teranary st"
},
{
"path": "conditionalfunctioncall.py",
"chars": 223,
"preview": "#! /usr/bin/env python3\n\"\"\"calling different functions with same arguments based on condition\"\"\"\ndef product(a, b):\n "
},
{
"path": "controlwhitespaces.py",
"chars": 510,
"preview": "#! /usr/bin/env python3\n\"\"\"control the whitespaces in string\"\"\"\n\ns = 'The Little Price'\n\n# justify string to be at least"
},
{
"path": "copylist.py",
"chars": 320,
"preview": "#! /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"
},
{
"path": "dictionaryget.py",
"chars": 131,
"preview": "#! /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"
},
{
"path": "dictsortbyvalue.py",
"chars": 451,
"preview": "#!/usr/bin/env python3\n\"\"\" Sort a dictionary by its values with the built-in sorted() function and a 'key' argument. \"\"\""
},
{
"path": "dictswapkeysvalues.py",
"chars": 230,
"preview": "#! /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 va"
},
{
"path": "exec.py",
"chars": 169,
"preview": "#! /usr/bin/env python3\n\"\"\"exec can be used to execute Python code during runtime\nvariables can be handed over as a dict"
},
{
"path": "extendediterableunpacking.py",
"chars": 251,
"preview": "#! /usr/bin/env python3\n\"\"\"allows collecting not explicitly assigned values into \na placeholder variable\"\"\"\n\na, *b, c = "
},
{
"path": "flattenlist.py",
"chars": 752,
"preview": "#! /usr/bin/env python3\n\"\"\"\nDeep flattens a nested list\n\nExamples:\n >>> list(flatten_list([1, 2, [3, 4], [5, 6, [7]]]"
},
{
"path": "forelse.py",
"chars": 205,
"preview": "#! /usr/bin/env python3\n\"\"\"else gets called when for loop does not reach break statement\"\"\"\na = [1, 2, 3, 4, 5]\nfor el i"
},
{
"path": "keydefaultdict.py",
"chars": 442,
"preview": "\"\"\"\nkeydefaultdict with where the function recieves the key.\n\"\"\"\nfrom collections import defaultdict\n\n\nclass keydefaultd"
},
{
"path": "lightweightswitch.py",
"chars": 306,
"preview": "#! /usr/bin/env python3\n\"\"\"lightweight switch statement\"\"\"\na = {\n True: 1,\n False: -1,\n None: 0\n}\nprint(a.get(F"
},
{
"path": "listtocommaseparated.py",
"chars": 318,
"preview": "#! /usr/bin/env python3\n\"\"\"converts list to comma separated string\"\"\"\n\nitems = ['foo', 'bar', 'xyz']\n\nprint (','.join(it"
},
{
"path": "loopoverlappingdicts.py",
"chars": 426,
"preview": "#! /usr/bin/env python3\n\"\"\"loop over dicts that share (some) keys in Python2\"\"\"\n\ndctA = {'a': 1, 'b': 2, 'c': 3}\ndctB = "
},
{
"path": "maxsplit.py",
"chars": 204,
"preview": "#! /usr/bin/env python3\n\"\"\"split a string max times\"\"\"\nstring = \"a_b_c\"\nprint(string.split(\"_\", 1))\n\n\n\"\"\"use maxsplit wi"
},
{
"path": "metatable.py",
"chars": 504,
"preview": "\"\"\"\nmetatable with where the function recieves the dictionary and key.\n\"\"\"\nfrom collections import defaultdict\n\n\nclass m"
},
{
"path": "minmaxindex.py",
"chars": 300,
"preview": "\"\"\"\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="
},
{
"path": "namedformatting.py",
"chars": 478,
"preview": "#! /usr/bin/env python3\n\"\"\"easy string formatting using dicts\"\"\"\n\nd = {'name': 'Jeff', 'age': 24}\nprint(\"My name is %(na"
},
{
"path": "nested_functions.py",
"chars": 204,
"preview": "#!/usr/bin/env python3\n\"\"\"nested functions\"\"\"\ndef addBy(val):\n def func(inc):\n return val + inc\n return fun"
},
{
"path": "objgetnamedattribute.py",
"chars": 150,
"preview": "#! /usr/bin/env python3\n\"\"\" Return the value of the named attribute of an object \"\"\"\nclass obj():\n attr = 1\n\nfoo = \"a"
},
{
"path": "rawinputintegers.py",
"chars": 236,
"preview": "#! /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(\"### In"
},
{
"path": "removeduplicatefromlist.py",
"chars": 342,
"preview": "#! /usr/bin/env python3\n\"\"\"remove duplicate items from list. note: does not preserve the original list order\"\"\"\n\nitems ="
},
{
"path": "reverselist.py",
"chars": 218,
"preview": "#! /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"
},
{
"path": "setglobalvariables.py",
"chars": 139,
"preview": "#! /usr/bin/env python3\n\"\"\"set global variables from dict\"\"\"\n\nd = {'a': 1, 'b': 'var2', 'c': [1, 2, 3]}\nglobals().update"
},
{
"path": "setoperators.py",
"chars": 737,
"preview": "#! /usr/bin/env python3\n\"\"\"Python provides usual set operator\"\"\"\na = set(['a', 'b', 'c', 'd'])\nb = set(['c', 'd', 'e', '"
},
{
"path": "socketmsghandling.py",
"chars": 452,
"preview": "import socket\nimport functools\n\ns = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\nconn = s.connect(('localhost', 80)"
},
{
"path": "sortlistkeepindices.py",
"chars": 551,
"preview": "#! /usr/bin/env python3\n\"\"\"Sort a list and store previous indices of values\"\"\"\n\n# enumerate is a great but little-known "
},
{
"path": "stepslice.py",
"chars": 107,
"preview": "#! /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",
"chars": 194,
"preview": "#! /usr/bin/env python3\n\"\"\"transpose 2d array [[a,b], [c,d], [e,f]] -> [[a,c,e], [b,d,f]]\"\"\"\n\noriginal = [['a', 'b'], ['"
},
{
"path": "tree.py",
"chars": 260,
"preview": "#! /usr/bin/env python3\n\"\"\"\nSee description here \nhttps://gist.github.com/hrldcpr/2012250\n\"\"\"\n\nfrom collections import d"
},
{
"path": "tryelse.py",
"chars": 373,
"preview": "\"\"\" You can have an 'else' clause with try/except. \n It gets excecuted if no exception is raised.\n This allows you"
},
{
"path": "unique_by_attr.py",
"chars": 631,
"preview": "#! /usr/bin/env python3\n\"\"\"\n If we have some sequence of objects and want to remove items with the same attribute val"
},
{
"path": "valueswapping.py",
"chars": 110,
"preview": "#! /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",
"chars": 265,
"preview": "\"\"\" You can have an else clause with a while. Works like for-else.\n When break is encountered, it exits the loop with"
}
]
About this extraction
This page contains the full source code of the pochmann/PyTricks GitHub repository, extracted and formatted as plain text for AI agents and large language models (LLMs). The extraction includes 45 files (15.4 KB), approximately 5.5k tokens, and a symbol index with 26 extracted functions, classes, methods, constants, and types. Use this with OpenClaw, Claude, ChatGPT, Cursor, Windsurf, or any other AI tool that accepts text input. You can copy the full output to your clipboard or download it as a .txt file.
Extracted by GitExtract — free GitHub repo to text converter for AI. Built by Nikandr Surkov.