Post ARVMsIQ5EMBKXOos7c by bonifartius@qoto.org
(DIR) More posts by bonifartius@qoto.org
(DIR) Post #ARVFrvj2uKQATRZFDc by lorenzo@neuromatch.social
2023-01-10T13:01:18Z
1 likes, 3 repeats
Posting this because it can save some lives. If you use an empty list or dictionary as a default argument in #python, the same list will be used every time. So every call will just update the mutable element instead of re-defining it as empty 😱Most IDEs will give you a vague warning (PyCharm does) but nothing more so it can be very sneaky and dangerous!#coding #programming #killerbugs
(DIR) Post #ARVFxZJHA3lsgsCbdw by ML2@akkoma.sandhill.social
2023-01-10T14:44:23.052021Z
0 likes, 0 repeats
@lorenzo By habit I use a default argument of None together with something likeif x == None: x = []...
(DIR) Post #ARVIvJQxW6qOjdPbE0 by lorenzo@neuromatch.social
2023-01-10T15:15:43Z
1 likes, 0 repeats
@ML2 Yes that's the correct pattern! Someone once told me to use "is None" since "is" is not overloadable (the == operator is) but I guess it doesn't make much difference in practice.
(DIR) Post #ARVMsIQ5EMBKXOos7c by bonifartius@qoto.org
2023-01-10T16:01:51Z
0 likes, 0 repeats
@lorenzo python is so easy and beginner friendly! :)
(DIR) Post #ARVOBm5tE5q41kE52W by PawelK@noagendasocial.com
2023-01-10T16:16:34Z
0 likes, 0 repeats
@lorenzo Awwww crap. Funny side effect.
(DIR) Post #ARVV51dRkGytsaePRI by joshburnett@fosstodon.org
2023-01-10T13:14:20Z
1 likes, 0 repeats
@lorenzoNote that this is an issue with any mutable default argument, not just lists. Dictionaries, non-frozen dataclasses, etc, will all result in this same behavior. Definitely a tricky gotcha to be aware of!