Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

default argument values are cached #29

Open
MichaelCook opened this issue Mar 16, 2024 · 0 comments · May be fixed by #31
Open

default argument values are cached #29

MichaelCook opened this issue Mar 16, 2024 · 0 comments · May be fixed by #31

Comments

@MichaelCook
Copy link

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()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant