Search code examples
pythonpython-3.xpython-datetime

Python datetime.now() as a default function parameter return same value in different time


Now I got some problem that I can't explain and fix.
This is my first python module

TimeHelper.py

from datetime import datetime

def fun1(currentTime = datetime.now()):
    print(currentTime)

and another is

Main.py

from TimeHelper import fun1
import time

fun1()
time.sleep(5)
fun1()

When I run the Main.py, the out put is
2020-06-16 09:17:52.316714
2020-06-16 09:17:52.316714

My problem is why the time will be same in the result ? Is there any restrict when passing datetime.now() in to default parameter ?


Solution

  • I think I find the answer. Thanks for @user2864740
    So I change my TimeHelper.py to this

    from datetime import datetime
    
    def fun1(currentTime = None):
        if currentTime is None:
            currentTime = datetime.now()
        print(currentTime)
    

    and anything work in my expectation.