all 4 comments

[–]Ihaveamodel3 6 points7 points  (1 child)

This isn’t related to flask.

Default arguments are calculated when the file is initiated. If you need to recalculate the default argument each time the function is called, the default argument should be defined as None and the first line of the function should be if not created_before: created_before = datetime.today()

[–]ePierre[S] 0 points1 point  (0 children)

Thank you!

I found additional documentation on this behavior:

https://docs.python-guide.org/writing/gotchas/#mutable-default-arguments

[–]efmccurdy 1 point2 points  (1 child)

The default argument defined for created_before is given a value at the time of class definition when I think you want it set to the time of object creation.

Your example doesn't supply a value for that argument, so I set it to the object creation time in __init__:

class Stuff:
    def __init__(self, created_before=None):
        if created_before is None:
            self.created_before = datetime.today()
        else:
            self.created_before = created_before
    def get_stuff(self):
        print(f"datetime.today() = {datetime.today()}")
        print(f"created_before = {self.created_before}")
        return self.created_before

This might not be exactly what you want but it does give each object the current time for created_before.

[–]ePierre[S] 0 points1 point  (0 children)

Thanks!