Function to avoid a global variable
ast
ast at invalid
Tue Apr 28 02:51:19 EDT 2020
Le 27/04/2020 à 04:46, Bob van der Poel a écrit :
> Does this make as much sense as anything else? I need to track calls to a
> function to make sure it doesn't get called to too great a depth. I had a
> global which I inc/dec and then check in the function. Works fine, but I do
> need to keep a global around just for this.
>
> So ... instead I wrote a short function:
>
> def parseStack(inc, depth=[0]):
> if depth[0] > 50:
> ... report error and die nicely
> depth[0] += inc
>
> This gets rid of the global, and it moves my error check out of the main
> code as well. But, I never feel all that great about using a list in the
> function call for static storage.
>
Using a callable object is the best way to define a function
with a memory
class ParseStack:
def __init__(self):
self.depth=0
def __call__(self, inc, reset=True):
if reset:
self.depth = 0
if self.depth > 50:
... report error
self.depth += 1
... do your stuff
parse_stack = ParseStack()
and use "function" parse_stack
parse_stack(43)
...
More information about the Python-list
mailing list