This is more a note to self, sometimes it makes sense to not use an iterable. While switching to a namedtuple won't make the task of programming routines easier, any prudent student of the language will instantly notice that employing a namedtuple can increase readability especially for parsing csv. I think it's really cool that the class creation is abstracted away, and can't wait to use it on the next project to call for it.
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
# http://docs.python.org/library/collections.html | |
# note to self | |
import collections | |
from collections import namedtuple | |
Robot = namedtuple('Robot', 'base, hinge1, arm_len, hinge2, wrist, hand') | |
Robot.base = 260 | |
Robot.hinge1 = 20 | |
Robot.arm_len = 120 | |
Robot.hinge2 = 150 | |
Robot.wrist = 90 | |
Robot.hand = 0 | |
# not an iterable. | |
print(Robot.hinge2) |
" my main annoyance with named tuples is they're implemented in python so they're not as fast as builtin types like dicts."
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
# as suggested and clarified by Campbell Barton, in the first response to this post. | |
# Here's an example of a helper function to do new classes that work like named tuples | |
# ---- | |
# 1 liner for making new named tuple like classes | |
def auto_class(name, slots): return type(name, (object, ), {"__slots__": slots}) | |
mytype = auto_class("TrickyClass", ("blah", "whee", "whoo")) | |
t = mytype() | |
t.whoo = 10 | |
print(t.whoo) |
Edit 2014: Amazingly.. there are easier ways
Almost 4 years on and I can safely say I've used neither method - ever. What I have used repeatedly is
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
theme = lambda: None | |
theme.col_background = '#e7e7e7' | |
theme.col_header = '#707070' | |
theme.col_stroke = '#000' | |
theme.hide_tick = '#888' |
lambda: None
might look a little weird the first few times.