3 ms·
Well, any Python developer worth his salt knows that initializing default parameters that way is a big no-no. I actually use code with those exact mistakes in i
by GuiA 13y ago
Well, any Python developer worth his salt knows that initializing default parameters that way is a big no-no. I actually use code with those exact mistakes in interviews, as it is a good way to tell Python beginners from more enlightened users.
- raverbashing 13y agoCorrect Unfortunately a lot of people still use it (and it's actually correct, IF you don't modify it) It's a risk not worth taking (to me, at least)
- klibertp 13y agoThat's the only way of creating function with state without introducing closure or making an object with __call__. It's very handy for accumulators and other bits of state which are inherent to the function you write. It's essentially a `static` variable declared inside a function in C and believe it or not it has it's uses. Depending on a problem it can be worthwhile to use other techniques of creating stateful callables, but that doesn't mean you should never create a function with mutable default argument. It's there in the language - learn about it, understand how it works and why it works like this, then understand where to use it and use it where it makes sense. That's a pretty generic advice, valid for almost any language feature.
- leohutson 13y ago> That's the only way of creating function with state without introducing closure or making an object with __call__ What about this? def foo(): if not hasattr(foo, 'static_list'): foo.static_list = [] At least it's a bit easier to see that something funky is going on.
- dbaupp 13y agoIt's easy to make mistakes, especially when the compiler/interpreter gives no assistance/warnings.
- MBlume 13y agoPylint catches this, pylint categorizes this as a warning. If your language has a lint tool and your code is remotely important, please run the lint tool as part of your build.
- mpyne 13y agoThe "No True Scotsman" helps out for essentially every language though.