Python pearls required for iteration across fields of data structure

N

NetHead

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
 
M

Marc 'BlackJack' Rintsch

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?

[…]
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

Maybe you shouldn't silence all exceptions with a bare except here. This
swallows any errors in `replaceFieldsAndIndices()`. Maybe some of them
are not the exception you expect, but real errors in your program!?

Ciao,
Marc 'BlackJack' Rintscj
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,769
Messages
2,569,579
Members
45,053
Latest member
BrodieSola

Latest Threads

Top