Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Check a tuple for containing a mutable object #3090

Closed
KonsKo opened this issue Nov 10, 2024 · 2 comments
Closed

Check a tuple for containing a mutable object #3090

KonsKo opened this issue Nov 10, 2024 · 2 comments
Labels
rule request Adding a new rule

Comments

@KonsKo
Copy link

KonsKo commented Nov 10, 2024

Rule request

Hello,
I would like to suggest a new rule. I could not find it in the existing rules, but if it exists so, sorry for duplication.

Thesis

I am proposing a new check for a tuple if a tuple contains a mutable object.

Python 3.12.7 (...) [Clang 15.0.0 (clang-1500.3.9.4)] on darwin
mutable_variable: list = [1, 2, 3]
tuple_variable: tuple = (1, 2, 3, mutable_variable)
tuple_variable
(1, 2, 3, [1, 2, 3])
mutable_variable[0] = 'new_val'
tuple_variable
(1, 2, 3, ['new_val', 2, 3])

Reasoning

It is dangerous to use tuples with mutable objects. And I think it may help many people to understand it.
We expects immutable behavior from a tuple.
But we know that for container-like sequences (for our case for a tuple), all elements are held by reference.
When we put a mutable container-like sequence into a tuple, and after that we change value of it, tuple will be changed.
It may look like unexpected behavior and may lead to errors.

@KonsKo KonsKo added the rule request Adding a new rule label Nov 10, 2024
@KonsKo KonsKo changed the title Check a tuple for containing mutable object Check a tuple for containing a mutable object Nov 11, 2024
@sobolevn
Copy link
Member

Good idea, thank you!

@sobolevn
Copy link
Member

Turns out that a lot of API rely on that: django settings, pytest fixtures, etc.

Sadly, I cannot make it good enough not to raise a lot of false-positives.

@sobolevn sobolevn closed this as not planned Won't fix, can't repro, duplicate, stale Dec 24, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
rule request Adding a new rule
Projects
None yet
Development

No branches or pull requests

2 participants