3 ms·
module-level dict?... why...
by codesnik 6y ago
module-level dict?... why...
- davesque 6y agoUh...that's my point. Everyone new to Python has to eventually learn not to do that.
- PartiallyTyped 6y agoThe folk over at openAI do something similar in order to create a registry, so that you can initialize objects using a name.
- carapace 6y agoIt's a simple rule: Default arguments are evaluated at function definition time (when the interpreter reaches the 'def' statement) not at the time the function is called. It's not a "module-level dict", you can create functions inside other functions: def foo(): def bar(a={}): ... return bar Each instance of bar gets its own dict when you run foo() and the "def bar(...): ..." statement gets executed. The dict is packaged up inside the function object (sort of like a closure except that the dict and it's name aren't from the enclosing scope of the function, and of course you can "shadow" it by passing in an argument for the parameter. https://en.wikipedia.org/wiki/Closure_(computer_programming) https://en.wikipedia.org/wiki/Closure_(computer_programming) )
- codesnik 6y agoI understand this simple rule, and I understand closures, of course, it's just using closure semantics for default arguments doesn't make any sense, aside from some optimization maybe, and pretty dangerous. Other approaches are possible, see ruby, for example, default arguments are evaluated basically as if they're already in the body of running function, every time, only when they're not passed, and with the same lexical scope as the function/method. And what, python retained this behavior even in 3.x? omg.
- carapace 6y agoAh, sorry for over-explaining.