Python pearls required for iteration across fields of data structure

NetHead edzietarski at hotmail.com
Tue Jul 24 05:26:15 EDT 2007


I want to apply a method (replaceFieldsAndIndices) in my class to a
number of attributes of a data structure.

Specifically, to give some context, in the variable j below, I want to
replace wildcards with values.

I wanted to avoid cluttering the code with multiple calls to the
method replaceFieldsAndIndices.

The code below is WRONG, but hopefully illustrates what I am trying to
achieve.

Any suggestions how to code this is an efficient and maintainable (and
correct) manner?

# BAD code begins
wildcards = None
if trap:
        for c in translation.expressionList:
                wildcards += (c.rpn, c.format)
        for c in translation.conditionList:
                wildcards += (c.match, c.min, c.max, c.format)
else:
        for c in translation.conditionRuleList:
                wildcards += (c.format, c.condition, c.expression)
        for c in translation.rules:
                wildcards += (c.match, c.min, c.max, c.bit, c.format)

for i in wildcards:
        for j in i:
                try:
                        j = self.replaceFieldsAndIndices(j, rcn, rcu,
rcp, indices)
                except:
                        # Ignore errors if condition has no format.
                        pass
# BAD code ends




More information about the Python-list mailing list