Using Python Reflection
May 15, 2021
I recently had an issue that I was able to solve using Python reflection. I've used reflection in the past when writing Java and was happy to see that it was possible in Python. It fit this issue very well.
The problem was to determine if any of a known list of attributes was not being used by a Partner object. If an attribute is True, it is being used. To make the code more efficient, any attributes found could be removed from the attribute list so the check of the next partner was faster. The function I used was...
def check_field_names(self, partner, field_names):
attributes_to_remove = 
for attribute in field_names:
attr_value = getattr(partner, str(attribute))
if str(attr_value) == 'True':
return [x for x in field_names if x not in attributes_to_remove]
The code loops through the attribute names and checks if the partner has the attribute set to True. The reflection part is the line:
attr_value = getattr(partner, str(attribute)) . If the attribute is found, it is added to the
attributes_to_remove and a list comprehension removes those items from the list and returns the shortened list to the calling function.
This was my first opportunity to use reflection in Python and it was a great solution to this problem.