Skip to content

Instantly share code, notes, and snippets.

View judy2k's full-sized avatar

Mark Smith judy2k

View GitHub Profile
@judy2k
judy2k / auto_args.py
Created April 18, 2017 13:48
Save constructor arguments on self without writing self.x = x etc...
from inspect import signature
def auto_args(f):
sig = signature(f) # Get a signature object for the target:
def replacement(self, *args, **kwargs):
# Parse the provided arguments using the target's signature:
bound_args = sig.bind(self, *args, **kwargs)
# Save away the arguments on `self`:
for k, v in bound_args.arguments.items():
if k != 'self':
@judy2k
judy2k / audience.md
Last active April 16, 2017 18:43
Refactoring Talk Outline

This talk is aimed at intermediate Python developers who are interested in developing & maintaining Python libraries. The audience should understand core Python reasonably well, and be aware of things like the property decorator and what "dunder-methods" are.

The audience will learn how to structure their project and their code in ways that will allow them to make changes later without breaking their users' code. Hopefully they'll come away thinking about the structure of their library code in a clearer way.

@judy2k
judy2k / tweet-syntax
Last active March 30, 2017 09:36
Generate a syntax-highlighted code snippet for Twitter
#!/bin/bash -e
#
# tweet-syntax - Create a syntax-highighted PNG file of your code and save in /tmp
#
# Prerequisites:
# pip install --upgrade pygments pillow
# 'Source Code Pro' font (or change the script below)
#
# Usage: cat code.ext | tweet-syntax [<syntax>]
@judy2k
judy2k / monkey-patch.py
Created March 16, 2017 09:55
Monkey Patching Functions
# So, a bit like mocking/patching, it depends on how the thing you're patching is imported *where it's used*.
# If the code that uses it is in a module called `client`, you'd want to do one of the following:
# If client.py looks like this:
from django.things import victim
def useful_function():
victim(blah)
@judy2k
judy2k / magic_precedence.py
Created September 1, 2016 15:56
Demonstrates that data descriptors have precedence over the instance dict.
class NonDataDescriptor(object):
def __get__(self, *args, **kwargs):
return 'magic'
class DataDescriptor(object):
def __get__(self, *args, **kwargs):
return 'magic'
def __set__(self, *args, **kwargs):
pass
@judy2k
judy2k / test_transfer_dict.py
Last active August 18, 2016 08:14
A handy function for copying properties from one dict to another with optional key mapping. Small amount of code, and well tested.
from transfer_dict import transfer_dict
SOURCE = {
'a': 'thing',
'key': 'value',
}
def test_basic():
dest = transfer_dict(SOURCE)
assert dest == SOURCE
@judy2k
judy2k / argparse_call.py
Created April 10, 2016 10:45
argparse -> function call
# Please note this function is a sketch and there will be (plenty of) edge cases
# where it won't do the right thing.
def whitelist_dict(d, whitelist):
"""
Neat function to extract arguments from a dict, d, that are acceptable for
calling a target function.
`whitelist` can be either a set of acceptable parameter names, or a callable,
which will have its parameters inspected.
@judy2k
judy2k / next_weekday.py
Created January 9, 2016 11:54
Find the next weekday after the given date.
from datetime import date, timedelta
def next_weekday(d):
wd = d.weekday()
return d + timedelta(days=1 if wd < 4 else 7 - wd)
@judy2k
judy2k / unicode.md
Last active December 31, 2015 02:09
These are some notes for a potential short talk on Python & Unicode.

Python & Unicode

text = open('a_unicode_file.txt', 'r').read()
print text
print 'type:', type(text)       # str is a container for binary data
print 'bytes:', len(text)       # The number of bytes, not characters!
print ' '.join(repr(b) for b in text)
print 'first byte:', text[:1] # Prints an invalid character!
@judy2k
judy2k / double.py
Created March 26, 2013 15:55
The hackiest script in the world - anything that looks like an int in the input, replace with double its value and output to stdout. Use as follows (on OSX): 1. Copy the json data you want to double from your IDE 2. pbcopy | ./double.py | pbpaste 3. Paste the new json with all the numbers doubled back into your IDE
#!/usr/bin/env python
import re
import sys
def rep(sval):
return str(int(sval.group()) * 2)
if __name__ == '__main__':