Max
Max

Reputation: 4408

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

Upvotes: 0

Views: 823

Answers (2)

Niel Godfrey P. Ponciano
Niel Godfrey P. Ponciano

Reputation: 10699

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()

Upvotes: 2

blhsing
blhsing

Reputation: 106455

The default value of a parameter is evaluated at definition time in Python. To effectively make a default value evaluated at run time, a common approach is to set the default value to None and then use a condition to set it to a dynamically calculated value inside the function:

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

Upvotes: 1

Related Questions