Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

module-level dict?... why...


Uh...that's my point. Everyone new to Python has to eventually learn not to do that.


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) )


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.


Ah, sorry for over-explaining.


The folk over at openAI do something similar in order to create a registry, so that you can initialize objects using a name.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: