this post was submitted on 15 Jan 2025
84 points (98.8% liked)

Programmer Humor

33090 readers
292 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 

A small collection of WTF code snippets sorted by language.

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 25 points 2 weeks ago* (last edited 2 weeks ago) (1 children)

Python item 1

Mutable default arguments don't get re-initialized with each function call.

got an audible wtf from me... Been using python for years, totally unaware.

[–] [email protected] 9 points 2 weeks ago (1 children)

Mutating function arguments is pretty wtf to begin with.

[–] [email protected] 6 points 2 weeks ago* (last edited 2 weeks ago)

true, and i can't think of a legitimate case where it would have tripped me up. but if someone, a novice perhaps, wrote

def some_func(foo, bar=[1, 2, 3]):
    bar.reverse()  # for whatever reason
    print(bar)

some_func('hello')    # output [3,2,1]
some_func('hello')    # output [1,2,3] 

i think they would be within their rights to be surprised that calling this function twice has different results. that's what i was surprised by; it feels like bar would be re initialised each time with a scope of the function but apparenty not