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.

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."

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 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.

2 comments:

  1. Nifty, I always found it annoying to define classes just to access attributes in a nice way, dictionaries are fine but prefer to access as attributes - just less typing.

    my main annoyance with named tuples is the're implemented in python so the're not as fast as builtin types like dicts.

    Heres 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)

    ReplyDelete
  2. yep, that's beautiful. Thanks for the heads up, i will adjust my first post.

    ReplyDelete

Please use Blender.StackExchange.com for python scripting questions unrelated to this post.