more pythonic way
Barry
barry at barrys-emacs.org
Sat Feb 16 03:35:05 EST 2019
On 11 Feb 2019, at 20:00, Felix Lazaro Carbonell <felix at epepm.cupet.cu> wrote:
>> The most pythonic way is to do this:
>>
>> def find_monthly_expenses(month=datetime.date.today().month,
> year=datetime.date.today().year):
>> ...
This has subtle bugs.
The default is calculated at import time and not at function call time.
Also the defaults for month and year are not calculated at the same moment in time.
Import at 23:59:59.99 on 31 december 2018 and you might get
month as 12 and year as 2019.
Run this example to see the problem:
import datetime
import time
def test_defaults(prefix, now=datetime.datetime.now()):
print( prefix, now )
test_defaults('one')
time.sleep( 1 )
test_defaults('two')
time.sleep( 1 )
test_defaults('three', datetime.datetime.now())
Which outputs:
one 2019-02-16 08:30:54.819466
two 2019-02-16 08:30:54.819466
three 2019-02-16 08:30:56.821453
Notice that the time for 'one' and 'two' is the same.
Only the overridden default chanse.
Barry
More information about the Python-list
mailing list