Skip to content

Instantly share code, notes, and snippets.

@jl
Last active October 10, 2015 20:34
Show Gist options
  • Save jl/b668f6b300ae30236f10 to your computer and use it in GitHub Desktop.
Save jl/b668f6b300ae30236f10 to your computer and use it in GitHub Desktop.
Neat things you can do with namedtuples
import collections
Thing = collections.namedtuple('Thing', 'x y z a b c')
def get_by_id(db, thing_id):
columns = ','.join(Thing._fields) # "x,y,z,a,b,c"
qry = 'SELECT {} FROM things WHERE id=?'.format(columns)
row = db.execute(qry, (thing_id,)).fetchone()
return Thing(*row) # construct by expanding arguments
def print_thing(thing):
# As an iterable tuple, it can be used in list comprehension.
return '[{}]'.format(', '.join(str(f) for f in thing))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment