5 ms·
Is the explanation for #1 correct? "when the default value for a function argument is an expression, the expression is evaluated only once" I would explain th
by leephillips 13y ago
Is the explanation for #1 correct?
"when the default value for a function argument is an expression, the expression is evaluated only once"
I would explain the behavior he shows as due to the default value being mutable. I don't see an expression there, just an empty list used as a default.
- herge 13y agoThe default value is an expression which is executed when the module is instantiated, even if the expression results in an empty list. If I had: def f(now=datetime.datetime.now()): ... now would be the time when the module was loaded, not when f is called the first time, or when f is called after that, despite datetime objects being immutable.
- arethuza 13y agoIsn't that just now being bound to a different datetime object each time f is defined?
- mguillech 13y agoRight, it's (re) defined every time you call 'foo2' but that's a different scenario than the one written in the article (hadn't you had 'foo2' and only 'foo' then you'd have the same time in all your calls to the function without supplying arguments).
- kghose 13y agoimport datetime, time def foo2(): def foo(a=datetime.datetime.now()): time.sleep(1) return a return foo() for n in range(10): print foo2() 2014-05-08 11:23:01.642871 2014-05-08 11:23:02.644276 2014-05-08 11:23:03.644579 2014-05-08 11:23:04.645146 2014-05-08 11:23:05.646328 2014-05-08 11:23:06.647572 2014-05-08 11:23:07.647904 2014-05-08 11:23:08.648213 2014-05-08 11:23:09.648973 2014-05-08 11:23:10.649742 So, not quite module load time, but evaluation time.
- herge 13y agoYou are technically correct, the best type of correct. The top level function is evaluated at module load time.
- marcosdumay 13y agoKilink's comment apply again. If you define several functions at different times, the default argument will be evaluated each time you define a new function. You'll have the same behaviour if you keep reassigning lambdas at the same function name, or if you keep edditing the globals. You are misunderstanding how dynamic Python is. And, yes, the part about "module load time" was a simplification.
- hcarvalhoalves 13y agoActually, the explanation doesn't explain it all. In Python, variables are references (pointers). `[]` gets evaluated on import time, and returns a pointer to an object (an empty list). This object is then further mutated on the body on the next calls because if you don't pass the parameter, it still points to the same object.