Skip to content

Instantly share code, notes, and snippets.

View pykong's full-sized avatar
🎯
Focusing

Ben Felder pykong

🎯
Focusing
View GitHub Profile
@pykong
pykong / dict2xml.py
Last active December 10, 2017 18:52
Recursively transform even nested dicts to xml. (This is my own creation do not confuse with the dedicated library: https://pypi.python.org/pypi/dicttoxml) Plus: Tuple to xml converter.
from xml.etree.ElementTree import Element, tostring
def dict_to_xml(tag, d):
'''
Turn a simple dict of key/value pairs into XML
'''
elem = Element(tag)
for key, val in d.items():
if type(val) == dict:
# To be case-insensitive, and to eliminate a potentially large else-if chain:
m.lower().endswith(('.png', '.jpg', '.jpeg'))
@pykong
pykong / multi_kwargs.py
Created October 17, 2017 20:39
Python 3.5+ allows passing multiple sets of keyword arguments ("kwargs") to a function within a single call, using the `"**"` syntax.
>>> def process_data(a, b, c, d):
>>> print(a, b, c, d)
>>> x = {'a': 1, 'b': 2}
>>> y = {'c': 3, 'd': 4}
>>> process_data(**x, **y)
1 2 3 4
>>> process_data(**x, c=23, d=42)
@pykong
pykong / lazy_memo.py
Last active October 22, 2017 11:44
Can be used to implement memoization as well.
def mt(a, memo=[]):
a += 1
print(a)
memo.append(a)
print(memo)
mt(1)
mt(2)
mt(3)
@pykong
pykong / DictDelta.py
Last active October 31, 2017 14:44
Get all added, deleted or modified keys. DictDelata implements this in a stateful fashion.
class DictDelta:
'''Returns a list of ḱeys, which are added, deleted or whose values have been altered compared to the dict passed in the previous call.'''
def __init__(self):
self.old_dict = None
def __call__(self, new_dict):
"""Returns list of changed keys."""
# explicitly check for None, prevent all keys being returned on 1st run
sudo xed ~/.netrc
machine github.com
login USER_NAME
password ACCESS_TOKEN
machine api.github.com
login USER_NAME
password ACCESS_TOKEN
@pykong
pykong / boolean_indices.py
Created November 1, 2017 18:11
In Python, not only is 0 False and 1 True, but True is 1 and False is 0. This means you can do weird things like:
>>> a = 1
>>> (a==1) + (a>0) + (a==2)
2
@pykong
pykong / list_v_tuple.py
Created November 1, 2017 19:21
Be careful with single item tuples!
l = ['Your Code Here']
t = ('Your Code Here')
for item in l:
print(item)
for item in t:
print(item)
git add *
git status -s
git commit -m "YOUR COMMIT MESSAGE"
git push origin feature_name