Follow

Holy snakes, ! That's some gotcha. Did you expect this behavior? Why?

medium.com/geekculture/do-not-

TL;DR: if you create an object (an array or a class instance) in the declaration of a function as a default argument parameter, python creates it as it creates the function and then reuses it for subsequent calls.

That's great for atomic counters, but terrible for suppliers.

· · Web · 3 · 0 · 0

@aeveltstra yeah that's a pretty bad one.. Makes people have to write `None` and then inside the function `if None` somewhere a lot too...

@aeveltstra Yeah, that's bitten a few people I know, especially when they're first learning the language. :/

@aeveltstra it's actually one of the most widely known gotchas, judging by my own experience mentoring people.

@aeveltstra people also tend to panic when they see a mutable object in the arguments and replace it with the None dance described in the article, forgetting that if the function doesn't modify this argument, it may actually be okay.

Sign in to participate in the conversation
Mastodon

Server run by the main developers of the project 🐘 It is not focused on any particular niche interest - everyone is welcome as long as you follow our code of conduct!