Search code examples
pythonmethodsinitialization

How to use a imported method for initialization of default value in python?


I have a Helper.py that looks like this:

def toDayDate():
   return Now()    

def getAge(dob,today=toDayDate()):
  doMagic()

then I use it here:

from helper import getAge

input=getDOBfromUSER()
getAge(input)

The problem is when the Import is being interpreted by python the toDayDate() is run anyway!!!

What am I doing wrong here?

The above set up is so argument is set to a default dynamic


Solution

  • You might want to read on the following resources:

    When you declare it like this:

    def getAge(dob,today=toDayDate()):
    

    Quoting from those references:

    Python’s default arguments are evaluated once when the function is defined, not each time the function is called

    Let's prove it:

    >>> from datetime import datetime
    >>> 
    >>> 
    >>> datetime.now()  # Display the time before we define the function
    datetime.datetime(2021, 9, 28, 17, 54, 16, 761492)
    >>>
    >>> def func(var=datetime.now()):  # Set the time to now
    ...     print(var)
    ... 
    >>> func()
    2021-09-28 17:54:16.762774
    >>> func()
    2021-09-28 17:54:16.762774
    >>> func()
    2021-09-28 17:54:16.762774
    

    As you can see, even if we call func() after a few minutes, hours, or days, its value will be fixed to the time when we defined it, and wouldn't actually change upon every call. Also this proves that once you defined a function (or imported a file containing that function), its definition would already be assessed, which includes its default arguments. It wouldn't wait for you to call the function first before setting the default arguments.

    What you need to do is:

    def getAge(dob,today=None):
      if today is None:
        today = toDayDate()
      doMagic()
    

    Or perhaps you can take advantage of boolean short-circuiting:

    def getAge(dob,today=None):
      today = today or toDayDate()
      doMagic()