[getattr(x, contact_field_map[communication_type])for x in curr_role_group.contacts ifgetattr(x, contact_field_map[communication_type])]
The above is my list comprehension. The initial function and the filter clause call getattr twice. Will Python run this twice or does it optimize the calculation internally knowing it can cache the result after the first call?
If Python doesn't do the optimization, how can I rewrite it to run faster?
Python will run the getattr
twice -- It doesn't do any optimization (after all, how does it know that the first attribute fetch doesn't change the value of the second one?)
To optimize the query, you can do it in 2 stages. The first stage computes the values using a generator expression, the second stage filters those values:
gen = (getattr(x, contact_field_map[communication_type])for x in curr_role_group.contacts)
result = [item for item in gen if item]