Python value objects

When your Python class is essentially a bag of values creating a class for them is a lot of writing - because what you essentially want is to automatically store these values with as little fuzz as possible. So instead you can use the Python 2.6 collections.namedtuple trick.

So instead of doing it one of the old ways:

class Foo:
    bar = None
    gazonk = None

    def __init__(self, **kwargs):
        for k, v in kwargs.items():
            setattr(self, k, v)

You can now do it like this:

from collections import namedtuple
Foo = namedtuple('Room', 'bar gazonk')

You can now init your Foo class with either *args or **kwargs.

Be Sociable, Share!

You can follow any responses to this entry through the RSS 2.0 feed. Both comments and pings are currently closed.

AddThis Social Bookmark Button

Comments are closed.