Member-only story
Use None and Docstrings to Specify Dynamic Default Arguments
There might be instances where you need to employ a dynamic type as the default value of a keyword argument. Let’s consider an example function that sends a welcome email to a new user. You want to include the timestamp of when the user was added in the email. If the function is not provided this timestamp, it should use the current time as a default.
For example:
from time import sleep
from datetime import datetime
def send_welcome_email(user_email, time_added=datetime.now()):
email_body = f"Welcome! Your account was created on {time_added}"
# function to send the email to user_email with email_body goes here
print(email_body)
# Sending email to a new user
send_welcome_email("newuser1@email.com")
sleep(1)
send_welcome_email("newuser2@email.com")
sleep(1)
send_welcome_email("newuser3@email.com")
However, this approach would not work as expected because default argument values in Python are evaluated only once, at the time the function is defined.
As a result, every call to send_welcome_email()
without a provided time_added
would use the same timestamp: the time when the function was defined, not when it was called. If you execute the above…