On Fri, May 28, 2021 at 7:28 PM Ronald Oussoren via Python-ideas firstname.lastname@example.org wrote:
I honestly don’t see the difference between:
def spam(arg, static=): …
_static = 0 def spam(arg): global _static; …
The difference is where the state is stored. State in the latter example is less tightly coupled to the function and is easier to access externally, but for both cases there is a documented way to access them (spam.__defaults__[’static’] for the first example). In both cases there’s effectively a singleton object that stores data, which makes testing harder because it is harder to ensure the right preconditions for testing (e.g. some other code might have called the function and affected the function state in an unexpected way).
They're not very different if the function is itself global; you'd have to make sure you don't have a name collision with any other function that also uses global state, but other than that, they're basically going to behave the same way.
But if spam() is defined in any other context, it's no longer equivalent. The default argument is tied to the function object, not to its surrounding context. You could create five spam() functions in a loop, and each one has its own static value. You can't do that with global or nonlocal.