Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

August 26, 2011

namedtuple


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.

# 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)
addendum by Campbell Barton:
" my main annoyance with named tuples is they're implemented in python so they're not as fast as builtin types like dicts."

# 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
theme = lambda: None
theme.col_background = '#e7e7e7'
theme.col_header = '#707070'
theme.col_stroke = '#000'
theme.hide_tick = '#888'
view raw svgwrite2.py hosted with ❤ by GitHub
zero setup, zero hassle. A simple 'Null Lambda' Object, because it supports object attributes. lambda: None might look a little weird the first few times.