[portland] Seeking opinions on choosing data types: dictionary or instance attributes?
jeff at taupro.com
Wed Nov 28 13:00:09 CET 2007
Nick Welch wrote:
> Isn't UserDict pretty much a relic now, since new-style classes came
> around and let us inherit directly from dict?
Yes, UserDict is obsolete - subclassing from dict gives you more functionality
and better performance.
> On the original topic -- I've personally turned against abusing classes
> (or __getattr__) simply for the .foo.bar syntax. Dict key access may be
> a little more punctuationey, but it reminds you that you're dealing with
> just a plain ol' dictionary, and that always feels nice to me. If your
> classes are only there to contain some keys and values (and don't have
> any methods), then I feel that they fall into the category of needless
> syntactic sugar. If you just need a dict, then.. just use a dict!
One objective factor for choosing between attribute and dictionary access is
whether the key names are legal Python identifiers. If they are not, you
really want to use a dictionary rather than getattr(), in my opinion.
Using attribute access also gives you the option later of refactoring and
inserting special handling code.
Suppose you have:
x.firstname -> "Jeff"
x.lastname -> "Rush"
and one day you need the fullname. Just add to your container class:
return "%s, %s" % (self.lastname, self.firstname)
and you have:
x.fullname -> "Rush, Jeff"
Using a plain dictionary limits your flexibility in the future.
More information about the Portland