In C/C++, a function can declare a local variable as static
. When doing so, the value remains in memory and is available to subsequent calls to the function (this variable is no longer local, but that's besides the point).
Is there a way to do something similar in Python, without having to declare any global variable outside of the function?
Use case: a function that (among other things) uses a regex to extract a value from an input string. I want to pre-compile the pattern (re.compile()
), without having to declare the variable outside of the function scope.
I can inject a variable directly into globals()
:
globals()['my_pattern'] = re.compile(...)
But it doesn't look like a good idea.