2

At the moment I have a large section of code that looks like this:

daily_stats.Turnover = int(row[2])
daily_stats.Cars = int(row[0])
daily_stats.Cash = int(row[29])
daily_stats.Card = int(row[33])
daily_stats.Other = int(row[31]) + int(row[35]) + int(row[37])
daily_stats.Exit = int(row[43])
daily_stats.Manual = int(row[42])
daily_stats.Open = int(row[47])

This continues for about 30 lines and, while it gets the job done, isn't very tidy or pythonic.

Is there a cleaner way to do this in Python?

0

1 Answer 1

7

You could save your data in a dictionary and then iterate over it while using setattr to set the attributes in daily_stats.

In your dict the values could take either integers or lists (depending on whether they're a single value from row or multiple summed values). As such you can use a try:... except:... block to set a sensible value using setattr.

Below is a simplified version using random values. Note that it assumes that daily_stats supports setting normal arbitrary attributes.

class DailyStats(object):
    pass

row = ['10', '20', '30', '40', '50']

daily_stats = DailyStats()

items = {'Turnover':0,
         'Cars':1,
         'Cash':[2,3,4]}

for item, value in items.items():
    try:
        val = sum(int(row[val]) for val in value)
    except TypeError:
        val = int(row[value])
    setattr(daily_stats, item, val)

print(daily_stats.Turnover) # 10
print(daily_stats.Cars) # 20
print(daily_stats.Cash) # 120
Sign up to request clarification or add additional context in comments.

2 Comments

Not sure if it affects it, but I don't have control over the row[] variable, it comes from a CSV export of data from another service.
That shouldn't matter, as long as you can get its rows via row[whatever] then it should work fine. Mine is just a list because I had to create an example to work with.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.