Function to avoid a global variable

Chris Angelico rosuav at gmail.com
Tue Apr 28 03:13:39 EDT 2020


On Tue, Apr 28, 2020 at 4:56 PM ast <ast at invalid> wrote:
>
> 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)

"Best"? Not sure about that. Functions are first-class objects in
Python, so a function *is* a callable object. You don't have to create
a custom class with a call method just to be able to attach attributes
to your function.

ChrisA


More information about the Python-list mailing list