This post originated from an RSS feed registered with Python Buzz
by Ian Bicking.
Original Post: So many accessors...
Feed Title: Ian Bicking
Feed URL: http://www.ianbicking.org/feeds/atom.xml
Feed Description: Thoughts on Python and Programming.
Both Cheetah and ZPT's TALES
use a sort of soft sense of traversal. When you call
$person.address.city in Cheetah (or
person/address/city in TALES) that might be equivalent to
person().address().city(), or maybe
person['address'].city or person().address()['city']
or any number of combinations.
This is really convenient. You don't have to think too much about
what each object is. You are, after all, giving explicit names
(address, city), and these names explain just what you are trying to
do (different from if it meant person(address)[city]).
What's really the difference between a dictionary and an attribute? A
property and a method that takes zero arguments?
Part of the justification of this is that both Cheetah and ZPT/TALES
are for displaying information. Your template isn't supposed to
do anything, it's not supposed to have side-effects. So any
methods you call shouldn't matter. And attributes and dictionaries
have always been fuzzy -- every object has its __dict__ after
all.
But even in spite of these objects, what really is the value of these
different kinds of accessors? Does person.address really
mean something different than person['address']? And what
use is a method object really, do you often want to know what
person.address is in addition to
person.address()?
I think there are justifications for Python's various accessors, but I
also think there's real value in simplifying these. We have some of
that with property (and in one man's opinion, yay), and that
allows us to avoid many methods (my general policy is that getting a
property should never have side-effects, but otherwise zero-argument
methods are fair game for propertyization). The attribute/dictionary
distinction still exists, though.
I think my general rule will be: don't use __getitem__ unless
you really want to create something dictionary-like. (Or maybe if you
want to use attributes that aren't valid Python identifiers; then
__getitem__ and __getattr__ maybe should be synonyms)