Last active
October 10, 2015 20:34
-
-
Save jl/b668f6b300ae30236f10 to your computer and use it in GitHub Desktop.
Neat things you can do with namedtuples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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