List comprehension strangeness

Nicholas Cole nicholas.cole at gmail.com
Sun Jul 21 18:01:09 EDT 2019


I was profiling a slow function in an application last week, and came
across something that I still can’t explain. Inside a loop that was being
called 4 times, inside a for loop that ran for a few dozen times there was
a list compression of the form:

[x.id for x in some_function()]

According to the profiler, some_function was being called 52,000 times —
many, many times more than the few dozen it should have been. And sure
enough, removing the comprehension did indeed speed up the function.

It is very strange and feels like a possible bug in python. Has anyone ever
encountered anything similar?

Best wishes,

Nicholas



More information about the Python-list mailing list