Fast attribute/list item extraction
Robert Brewer
fumanchu at amor.org
Sun Nov 30 16:31:48 EST 2003
Peter Otten wrote:
> Following variants are possible:
>
> # extract an attribute
> extract.attr
Ick.
> extract(name="attr") # necessary when attribute name only
> known at runtime
Yes, it needs to be runtime-specifiable, for sure. I'd prefer:
extract("attr1", "attr2", ... "attrN")
returning a tuple, perhaps only if more than one attribute were
specified.
> extract[1]
> extract["key"]
Fine. Readable.
I'm having a hard time seeing the use cases, given that I find most of
them more readable if done with list comprehensions or good ol' for
loops. Everyone has their language-addition line-in-the-sand, and this
is looking "un-pythonic" to me; it seems to be obscuring code, not
revealing it.
Given current syntax, I tend to just provide _functions_ to sort() like
so:
def attr_sort(attrNames, descending=False):
"""Return a function which can be passed to list.sort()."""
# We can't simply try: iteration, because we don't want strings
# to be iterated over their characters. So we check type. :(
if type(attrNames) not in (type(()), type([])):
attrNames = (attrNames, )
def sort_func(x, y):
for eachName in attrNames:
try:
xv = getattr(x, eachName)
except AttributeError:
diff = -1
else:
try:
yv = getattr(y, eachName)
except AttributeError:
diff = 1
else:
diff = cmp(xv, yv)
if descending: diff = -diff
if diff != 0:
return diff
return 0
return sort_func
...obviously one might further trap the cmp() call, etc. This doesn't
really address the implementation of extract() as much as it says, "how
would extract() help sort()?"
Robert Brewer
MIS
Amor Ministries
fumanchu at amor.org
More information about the Python-list
mailing list