Skip to content

default argument values are cached #29

@MichaelCook

Description

@MichaelCook

Code like this:

def get_sunrise_time(self, at_date=datetime.now(), time_zone=timezone.utc):

isn't going to work right for long-running apps.
The default value for at_date gets saved when the function is parsed by the Python interpreter.
Thereafter, every invocation of get_sunrise_time() is going to use the same exact value for at_date.

You can see with this example:

from datetime import datetime
import time

def foo(when=datetime.now()):
  return when

print(foo())
time.sleep(3)
print(foo())

which prints the exact same value twice, something like this:

2024-03-16 15:27:59.125163
2024-03-16 15:27:59.125163

The fix is to do something like this:

def get_sunrise_time(self, at_date=None, time_zone=timezone.utc):
    if at_date is None:
        at_date = datetime.now()

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions