Tuesday Coding Tip 30 — Mutability in Python

●5 ●28 ●93
calendar_today • schedule1 min read
— Originally published at medium.com

Tuesday coding tips are super short posts about various tidbits mainly from C++, but also from other programming languages I use. You can also follow the #TuesdayCodingTips hashtag on Mastodon and Linkedin.


Mutability in Python is a hidden footgun for all programmers new to the language. Instead of it being explicit like in Rust or C++, Python tries to do the thing you probably, but not necessarily, want to do.

All primitive types — bools, numbers, and strings are always passed by value into functions. That means that if you change them inside, that change won’t affect the calling scope.

Objects, arrays, dictionaries, and other non-primitive types are always passed by mutable reference, meaning that changes to them will affect the caller.

def modify(myint, myarr, myobj, myobj2):
    myint = 10
    myarr[1] = 42
    myobj["newkey"] = "value"
    myobj2 = { "c": "c" } # overwrites pointer, no changes in caller scope

a = 0
arr = [ 0, 0, 0 ]
d = {
    "a": "a"
}
d2 = {
    "b": "b"
}
modify(a, arr, d, d2)
print(a) # Still 0
print(arr) # Now is [0, 42, 0]
print(d) # Now is {'a': 'a', 'newkey': 'value'}
print(d2) # Still the same {'b': 'b'}

Furthermore, copies of these objects are always shallow so changes to copies will also change the original. Luckily, there is a module that implements deep copy for you, at least for more common types.

import copy

d1 = {
    "a": 0
}

d2 = d1
d2["a"] = 42

print(d1) # d1 is {'a': 42}

d3 = copy.copy(d1) # deep copy
d3["a"] = 69

print(d1) # d1 is still {'a': 42}
print(d3) # d3 is {'a': 69}

Want more #python & #tuesday-coding-tips deep dives?

Join 6,001+ developers sharing real benchmarks, code breakdowns, and projects. Free forever.

Part 30 of 31 in Tuesday Coding Tips

2 Comments

1 vote
1

More Posts

Tuesday Coding Tip 06 - Explicit template instantiation

Jakub Neruda - Apr 7

Tuesday Coding Tip 02 - Template with type-specific API

Jakub Neruda - Mar 10

Dashboard Operasional Armada Rental Mobil dengan Python + FastAPI

Masbadar - Mar 12

When One Python Process Fails, You Need to See All of Them

Tom Smithverified - Nov 23

Tuesday Coding Tip 27 — Aliasing and ‘using’ in C++

Jakub Neruda - Oct 20
chevron_left
2.1k Points • 126 Badges
Brno, Czech Republic • linkedin.com/in/jakub-neruda
43Posts
37Comments
22Connections
Experienced C++ developer, team lead and hobby gamedev. I enjoy writing stuff about C++, clean code, clean architecture, and game development.

Commenters (This Week)

1 comment
1 comment

Contribute meaningful comments to climb the leaderboard and earn badges!