Reputation: 23
So I've been curious. I'm sooooomewhat new to python. I've been coding for over a year or so, but something I covered but didn't totally understand was the stigma that "global variables are bad."
That said, I was a beginner and couldn't understand any of the online explanations as to why I should avoid (or just be careful with) global variables. I just took everything everyone said to heart, and made the assumption that global variables are simply sinister monsters that prowl my code during runtime and eat all my data.
So I began to do the following:
>>> SomeVar = [0] # To avoid the 'global' keyword, I'll just make a single list item.
>>>
>>> def increment(): # Hey look, it's practically global!
>>> SomeVar[0] += 1
>>>
>>> increment()
>>> increment()
>>>
>>> SomeVar
[2]
After some time, I finally have the knowledge and experience to do some actual research on the matter, an I'm starting to get the impression I may have missed the point. I know globals take up namespace, can present issues in multithreading, and too many of them and/or too many functions accessing them at once can get hard to keep track of, but there's enough I still don't understand about them that I just wanted to ask;
Does my list-global-aversion variable actually help with the any of the issues global variables can present, or did I totally miss the point? I can see why it wouldn't do any good with the aforementioned issues, (multithreading, spaghetti code) but... does it help at all?
Thanks in advance!!
Upvotes: 2
Views: 52
Reputation: 77827
Yes, you've missed the point. What you created is still a global variable; all you did was work around the keyword.
When this expands to a full program, the initialization of Somevar
is likely to be widely separated from its usage. You've left your function dependent on an external variable of unknown location and provenance. instead, try this:
def increment(var): # Hey look, it's properly local!
return var + 1
somevar = 0
somevar = increment(somevar)
somevar = increment(somevar)
Upvotes: 3