Re:Pattern matching accepted for Python
by codesnik on Wednesday February 10, 2021 @01:23AM
(#26086193)
module-level dict?... why...
[ Parent
| on HN ]
Re:Pattern matching accepted for Python
by davesque on Wednesday February 10, 2021 @01:25AM
(#26086201)
Uh...that's my point. Everyone new to Python has to eventually learn not to do that.
Re:Pattern matching accepted for Python
by carapace on Wednesday February 10, 2021 @11:09AM
(#26091020)
It'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) )
Re:Pattern matching accepted for Python
by codesnik on Thursday February 11, 2021 @06:53PM
(#26109174)
I 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.
Re:Pattern matching accepted for Python
by carapace on Friday February 12, 2021 @11:10AM
(#26115154)
Ah, sorry for over-explaining.
Re:Pattern matching accepted for Python
by PartiallyTyped on Wednesday February 10, 2021 @06:04AM
(#26087713)
The folk over at openAI do something similar in order to create a registry, so that you can initialize objects using a name.