Skip to content

Avoid construction of objects in comprehensions without targets #151907

Description

@ZeroIntensity

Feature or enhancement

This is quite a silly micro-optimization.

For context, I ended up in a discussion about whether code like the following is a good idea:

[thread.join() for thread in threads]

Some people like the brevity over an explicit loop. The primary argument against this pattern is that this has the additional overhead of creating an additional list object (or set object for set comprehensions, dict for dict comprehensions). That made me wonder whether it was possible to simply omit the construction when the comprehension isn't used as a value. I managed to come up with a relatively small patch.

To be clear, I don't think this should be interpreted as an endorsement of this pattern. I, and probably many others, believe that for thread in threads: thread.join() is the better option, but that's beside the point; there are definitely people who do this in practice, and I think they'll enjoy the minor speedup.

Linked PRs

Metadata

Metadata

Assignees

No one assigned

    Labels

    interpreter-core(Objects, Python, Grammar, and Parser dirs)performancePerformance or resource usagetype-featureA feature request or enhancement
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions