Foxocube
Foxocube

Reputation: 740

Pythonic Variable Assignment

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?

Upvotes: 2

Views: 67

Answers (1)

Ffisegydd
Ffisegydd

Reputation: 53678

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

Upvotes: 7

Related Questions