Coding the Python way

Posted by Aaron Moodie on Stack Overflow See other posts from Stack Overflow or by Aaron Moodie
Published on 2010-05-31T03:47:32Z Indexed on 2010/05/31 3:52 UTC
Read the original article Hit count: 279

Filed under:
|
|

I've just spent the last half semester at Uni learning python. I've really enjoyed it, and was hoping for a few tips on how to write more 'pythonic' code.

This is the __init__ class from a recent assignment I did. At the time I wrote it, I was trying to work out how I could re-write this using lambdas, or in a neater, more efficient way, but ran out of time.

def __init__(self, dir):

        def _read_files(_, dir, files):

            for file in files:

                if file == "classes.txt":
                    class_list = readtable(dir+"/"+file)
                    for item in class_list:
                        Enrol.class_info_dict[item[0]] = item[1:]
                        if item[1] in Enrol.classes_dict:
                            Enrol.classes_dict[item[1]].append(item[0])
                        else:
                            Enrol.classes_dict[item[1]] = [item[0]]

                elif file == "subjects.txt":
                    subject_list = readtable(dir+"/"+file)
                    for item in subject_list:
                        Enrol.subjects_dict[item[0]] = item[1]

                elif file == "venues.txt":
                    venue_list = readtable(dir+"/"+file)
                    for item in venue_list:
                        Enrol.venues_dict[item[0]] = item[1:]

                elif file.endswith('.roll'):
                    roll_list = readlines(dir+"/"+file)
                    file = os.path.splitext(file)[0]
                    Enrol.class_roll_dict[file] = roll_list
                    for item in roll_list:
                        if item in Enrol.enrolled_dict:
                            Enrol.enrolled_dict[item].append(file)
                        else:
                            Enrol.enrolled_dict[item] = [file]


        try:
            os.path.walk(dir, _read_files, None)
        except:
            print "There was a problem reading the directory"

As you can see, it's a little bulky. If anyone has the time or inclination, I'd really appreciate a few tips on some python best-practices.

Thanks.

© Stack Overflow or respective owner

Related posts about python

Related posts about best-practices