tags:

views:

57

answers:

1

I'm going to create statistics based on information what builds were success or not and how much per project.

I create ProjectStat class per new project I see and inside handled statistics. For printing overall statistic I need to pass through all ProjectStat instances. For printing success statistics per project I need to pass through them again and so on, on any kind of statistics. My question is about simplifying the way handling the cycles, i.e not to pass the dictionary every time. Perhaps using decorators or decorator pattern would be pythonic way? How then they can be used if number of instances of ProjectStat is dynamically changed?

Here is the code:

class ProjectStat(object):
 projectSuccess = 0
 projectFailed = 0
 projectTotal = 0

def addRecord(self, record):
    if len(record) == 5: record.append(None)
    try:
        (datetime, projectName, branchName, number, status, componentName) = record
    except ValueError:
        pass
    self.projectTotal += 1
    if status == 'true': self.projectSuccess += 1
    else: self.projectFailed += 1
def addDecorator(self, decorator):
    decorator = decorator


def readBuildHistoryFile():
dict = {}
f = open("filename")
print("reading the file")
try:
    for line in f.readlines():
        #print(line)
        items = line.split()
        projectName = items[1]
        projectStat = dict[projectName] = dict.get(projectName, ProjectStat())
        projectStat.addRecord(items)
        print(items[1])
finally:
    f.close()

success = 0
failed = 0
total = 0

for k in dict.keys():
    projectStat = dict[k]
    success += projectStat.projectSuccess
    failed += projectStat.projectFailed
    total += projectStat.projectTotal

print("Total: " + str(total))
print("Success: " + str(success))
print("Failed: " + str(failed))

if __name__ == '__main__':
 readBuildHistoryFile()
+1  A: 

I'm not sure I understand the Q, but I'll try to answer anyway :)

option1:

total = sum([project.projectTotal for project in dict.values()])
success = sum([project.projectSuccess for project in dict.values()])
failed = sum([project.projectFailed for project in dict.values()])

option2:

(total,success,failed) = reduce (lambda x,y:(x[0]+y[0],x[1]+y[1],x[2]+y[2]), [(project.projectTotal,project.projectSuccess,project.projectFailed) for project in dict.values()])
Ofri Raviv
Thank you Ofri. Good technique for getting information. Now if I would like to get statistic per project then I will add print method to ProjectStat and call it using your advice. The only concern left if it's ok that I need every time go through the dictionary? For getting overall total, success, failure and then statistic per project after I will add print method, I need 4 times specify for cycle for dictionary and if there will be much records then it could consuming. What do you think?
yart
I don't think it is going to be a slow operation. first try it, and only if you get performance issues, try to optimize.
Ofri Raviv