r/backtickbot • • Jul 23 '21

https://np.reddit.com/r/Python/comments/opb7hm/do_not_use_mutable_objects_as_default_arguments/h67s46c/

You can give a plain function a static member by exploiting the fact that even a function itself is an object.

(I'm going to mess up the markdown, but here goes.)

def keep_a_total(n: int) -> int:
    keep_a_total.total += n
    return keep_a_total.total

keep_a_total.total = 0

Essentially, initialize the "static" as a member of the function object right after defining the function object.

1 Upvotes

0 comments sorted by