views:

112

answers:

6

Sometimes it makes sense to cluster related data together. I tend to do so with a dict, e.g.,

self.group = dict(a=1, b=2, c=3)
print self.group[a]

One of my colleagues prefers to create a class

class groupClass(object):
    def __init__(a, b, c):
        self.a = a
        self.b = b
        self.c = c
self.group = groupClass(1, 2, 3)
print self.group.a

Note that we are not defining any class methods.

I like to use a dict because I like to minimize the number of lines of code. My colleague thinks the code is more readable if you use a class, and it makes it easier to add methods to the class in the future.

Which do you prefer and why?

+5  A: 

I prefer to follow YAGNI and use a dict.

Ignacio Vazquez-Abrams
+1  A: 

In a language which supports it, I would use a struct. A dictionary would be closest to a structure in Python, at least as far as I see it.

Not to mention, you could add a method to a dictionary anyway if you really wanted to ;)

Brian S
+6  A: 

If you're really never defining any class methods, a dict or a namedtuple make far more sense, in my opinion. Simple+builtin is good! To each his own, though.

Joe Kington
namedtuple's are great; just remember they're immutable. And don't forget if you do need to add class methods later, you can always just inherit from the result of namedtuple. E.g. `class Point(namedtuple('Point', 'x y')): ...`
Peter Milley
Great answers all around. I picked this one because I like the suggestion to try a namedtuple.
Jeff
+1  A: 

I disagree that the code is more readable using a class with no methods. You usually expect functionality from a class, not only data.

So, I'd go for a dict until the need for functionality arises, and then the constructor of the class could receive a dict :-)

Vinko Vrsalovic
+1  A: 

A dict is obviously appropriate for that situation. It was designed specifically for that use case. Unless you are actually going to use the class as a class, there's no use in reinventing the wheel and incurring the additional overhead / wasting the space of a class that acts as a bad dictionary (no dictionary features).

cookiecaper
+1  A: 

Your way is better. Don't try to anticipate the future too much as you are not likely to succeed.

However, it may make sense sometimes to use something like a C struct, for example if you want to identify different types rather than use dicts for everything.

Muhammad Alkarouri