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
tempvar = MyClassObject()
tempvar.this_field_was_not_defined_in_the_class = 42
Later on in the script, the variable tempvar is written to a CSV file by calling:
write_csv('test.csv', tempvar, ('declared_field1', 'declared_field2',
('declared_field3', 'New Label'),
'this_field_was_not_defined_in_the_class') )
Here is the (confusing [to me]) function that writes the object to file:
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])
Can anyone explain what is going on? BTW utf8ify and add_weighting are global functions defined in the script.
There are no “non-existent” attributes of an object. There are no declarations.
Attributes are merely assigned to objects in
__init__or in any code that references the object. That’s just standard Python.Perfectly normal. The attribute
new_attributeis not “non-existent” because it doesn’t need any kind of declaration.When you do
at the interactive prompt, you’ll see where attributes live.