(Python) Can some explain what this function is doing (use of object attributes)
<p>I am carrying out code maintenance on an old Python script. I have come accross a piece of the code, which has me flumoxed. Earlier on in the code (not shown in the snippet below), class are defined, with minimal attributes. Further on in the code, assignments are made to non existent fields in the class. For example</p>

<pre><code>tempvar = MyClassObject()
tempvar.this_field_was_not_defined_in_the_class = 42
</code></pre>

<p>Later on in the script, the variable tempvar is written to a CSV file by calling:</p>

<pre><code>write_csv('test.csv', tempvar, ('declared_field1', 'declared_field2',
                                ('declared_field3', 'New Label'), 
                                'this_field_was_not_defined_in_the_class') )
</code></pre>

<p>Here is the (confusing [to me]) function that writes the object to file:</p>

<pre><code>def write_csv(filename, objects, fields, add_weightings=True):
    # The items in fields can either be a tuple of the attribute name and a label for that
    # attribute, or just an attribute name. In the later case replace it with a tuple with an
    # automatically generated label.
    fields = list(fields)
    for i in xrange(len(fields)):
        if isinstance(fields[i], tuple):
            continue
        else:
            fields[i] = (fields[i], fields[i].replace('_', ' '))

    with open(filename, 'wb') as f:
        f.write(codecs.BOM_UTF8)
        c = csv.DictWriter(f, [i[0] for i in fields])
        c.writerow(dict(fields))
        c.writerows(
            [utf8ify(add_weighting(i.__dict__) if add_weightings else i.__dict__) for i in objects])
</code></pre>

<p>Can anyone explain what is going on? BTW <strong>utf8ify</strong> and <strong>add_weighting</strong> are global functions defined in the script.</p>
