Python paradigms

Andrew Dalke dalke at acm.org
Sun Apr 9 00:12:33 EDT 2000


I wrote:
>Nick Maclaren wrote
>>    x = (a != NULL ? a[i]->weeble : 0) + (b != NULL ? b[i]->wombat : 0)
>> [...]


>How about
>  x = getattr(a, "weeble", 0) + getattr(b, "wombat", 0)


My code, BTW, is wrong.  I didn't see the "[i]" part of the original
expression.  To my view of things, this means the expression is
too complex.

You asked about other idioms.  You could have a class wrapper
for accessing elements, like:

class SpecialLookup:
  def __init__(self, container, attr, default = 0):
    self.container = container
    self.attr = attr
    self.default = default
  def __getitem__(self, i):
    if self.container is None:
      return self.default
    return getattr(self.container[i], attr)

new_a = SpecialLookup(a, "weeble")
new_b = SpecialLookup(b, "wombat")
x = new_a[i] + new_b[i]

For slightly better performance, you could even create a special __getitem__
for empty containers so the check for a None container
is only done ones.

                    Andrew
                    dalke at acm.org






More information about the Python-list mailing list