Function to avoid a global variable

Chris Angelico rosuav at gmail.com
Sun Apr 26 23:47:22 EDT 2020


On Mon, Apr 27, 2020 at 1:39 PM Bob van der Poel <bob at mellowood.ca> wrote:
>
> 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.

That's not really any different from a global. If globals bother you,
this should as well. But it's also reasonable to NOT be bothered by it
- it's not that big a problem.

If this is directly recursive (if there's a call to parseStack inside
parseStack itself, as opposed to being mutually recursive with one or
more other functions), the easiest way to avoid the global is to just
pass the parameter down - something like this:

def spaminate(x, y, depth=0):
    ...
    spaminate(newx, newy, depth+1)
    ...

But that can be harder if you have other things happening, eg if your
function calls something else, which calls something else, which calls
your function again. If it's that complex, I would just accept the
global, honestly - globals (module-level variables) aren't the worst
thing that can happen. You won't end up with code reviews like
https://xkcd.com/1513/ just because of one global (or if you do, you
REALLY need to find better code reviewers!).

ChrisA


More information about the Python-list mailing list