Python Mutability
An exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
Syndicated from the fediverse. Read and engage on the original instance.
View original on programming.devAn exercise to help build the right mental model for Python data. The “Solution” link uses memory_graph to visualize execution and reveals what’s actually happening:
6 replies
It's always fun to guess whether python will call
__add__or__iadd__.__add__is called with+and__iadd__is called with+=, and there is a difference: https://www.reddit.com/r/PythonLearning/comments/1nw08wu/right_mental_model_for_python_data/Except if
__iadd__doesn't exist on the type, then__add__is called. The variable is always reassigned. Quick example:What is printed?
Thanks. I didn't know: https://memory-graph.com/#code=x+%3D+%280%2C+%5B1%2C+2%5D%29%0Atry%3A%0A++++x%5B1%5D+%2B%3D+%5B3%5D++%23+calls+list.__iadd__%2C+then+reassigns+x%5B1%5D%0Aexcept+TypeError+as+e%3A%0A++++print%28e%29%0A%0Ax+%2B%3D+%284%2C%29++%23+calls+tuple.__add__%2C+then+reassigns+x%0A%0Aprint%28x%29%0A%0A%0Aclass+MyClass%3A%0A++++%0A++++def+__add__%28self%2C+other%29%3A%0A++++++++print%28%27__add__%27%29%0A++++++++%0A++++%23def+__iadd__%28self%2C+other%29%3A%0A++++%23++++print%28%27__iadd__%27%29%0A%0Aa+%3D+MyClass%28%29%0Ab+%3D+MyClass%28%29%0Aa+%2B%3D+b++%23+calls+__add__+if+__iadd_+doesn%27t+exist%0A&play=
I so wonder what a will result in.
Yes
ayou get for free to set the tone, the others are more interesting.