Monday, March 16, 2009

Ruby's Struct v.s. Python's namedtuple

Hi, it is NISHIO Hirokazu. 9 years ago I met to Ruby's Struct. It is nice.


irb(main):018:0> FooBar = Struct.new(:foo, :bar)
=> FooBar
irb(main):019:0> FooBar.new(1, 2)
=> #<struct FooBar foo=1, bar=2>
irb(main):020:0> _.foo
=> 1


So I wrote its Python version.


>>> def Struct(*keys):
class _Struct(object):
def __init__(self, *values):
self.__dict__.update(zip(keys, values))
return _Struct


>>> Struct("foo", "bar")
<class '__main__._Struct'>
>>> FooBar = Struct("foo", "bar")
>>> FooBar(1, 2)
<__main__._Struct object at 0x01494E90>
>>> _.foo
1


Today I regret to inform the code is obsolete. In python2.6 we can use collections.namedtuple:


>>> from collections import namedtuple
>>> namedtuple("MyClass", "foo bar")
<class '__main__.MyClass'>
>>> _(1, 2)
MyClass(foo=1, bar=2)
>>> _.foo
1

No comments: