Skip to content

gh-154359: Optimize UserList type checks to use list directly#154358

Closed
pranavchoudhary-tech wants to merge 4 commits into
python:mainfrom
pranavchoudhary-tech:optimize-userlist-typecheck
Closed

gh-154359: Optimize UserList type checks to use list directly#154358
pranavchoudhary-tech wants to merge 4 commits into
python:mainfrom
pranavchoudhary-tech:optimize-userlist-typecheck

Conversation

@pranavchoudhary-tech

@pranavchoudhary-tech pranavchoudhary-tech commented Jul 21, 2026

Copy link
Copy Markdown
Contributor

This PR optimizes the type checking within UserList inside the collections module.

Since self.data is hardcoded to be an empty list [] at the beginning of UserList.__init__, the expression type(self.data) will always evaluate to the list type. We can replace type(initlist) == type(self.data) with a direct and more idiomatic type(initlist) is list identity check, bypassing the unnecessary type() call and attribute lookup while avoiding the slight anti-pattern of using the == operator to compare singleton type objects. The same optimization applies to the __add__, __radd__, and __iadd__ magic methods.

I ran the test_collections suite and verified that everything passes successfully with these changes.

Fixes #154359

@pranavchoudhary-tech pranavchoudhary-tech changed the title Optimize UserList type checks to use list directly gh-154359: Optimize UserList type checks to use list directly Jul 21, 2026
@pranavchoudhary-tech

Copy link
Copy Markdown
Contributor Author

Could a maintainer please apply the skip news label when they get a chance? This is just a minor internal optimization so I don't think a news entry is required.

@picnixz

picnixz commented Jul 21, 2026

Copy link
Copy Markdown
Member

Performance improvements must always be backed by benchmarks. I don't see value in this proposal for a class that is not used a lot and where this change could have broken existing code elsewhere (the attribute is still public).

@picnixz picnixz closed this Jul 21, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Optimize UserList type checks to use list directly

2 participants