5 ms·
The 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=
by herge 12y ago
The 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 12y agoIsn't that just now being bound to a different datetime object each time f is defined?
- mguillech 12y 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 12y 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 12y agoYou are technically correct, the best type of correct. The top level function is evaluated at module load time.
- marcosdumay 12y 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.