Function to avoid a global variable

Bob van der Poel bob at mellowood.ca
Mon Apr 27 12:39:08 EDT 2020


Thanks Chris!

At least my code isn't (quite!) as bad as the xkcd example :)

Guess my "concern" is using the initialized array in the function:

   def myfunct(a, b, c=array[0,1,2,3] )

always feels like an abuse.

Has anyone seriously considered implementing  a true static variable in a
function? Is there a PEP?

Best,

On Sun, Apr 26, 2020 at 8:47 PM Chris Angelico <rosuav at gmail.com> wrote:

> 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
> --
> https://mail.python.org/mailman/listinfo/python-list
>


-- 

**** Listen to my FREE CD at http://www.mellowood.ca/music/cedars ****
Bob van der Poel ** Wynndel, British Columbia, CANADA **
EMAIL: bob at mellowood.ca
WWW:   http://www.mellowood.ca


More information about the Python-list mailing list