-1

In my GUI application, I assign values to _register_allowed which is in the main function from a nested function inside main.

def toggle_registration():
    if _register_allowed:
        _register_allowed = False
    else:
        _register_allowed = True

this will then of course return a UnboundLocalError.

My question is, why is using the global declaration keyword to solve this a bad thing?

Since it achieves the same end result as nonlocal, i.e. that the value that the _register_allowed from outside the scope of the nested function is changed rather than a new local variable being created; why is this a bad, or un-Pythonic way to solve this?

John Smith
  • 65
  • 2
  • 11
  • 1
    Welcome to StackOverflow. [On topic](https://stackoverflow.com/help/on-topic), [how to ask](https://stackoverflow.com/help/how-to-ask), and ... [the perfect question](https://codeblog.jonskeet.uk/2010/08/29/writing-the-perfect-question/) apply here. Most important here is that we expect you to do appropriate research before posting here. This topic has been discussed heavily for over half a century. – Prune Jan 23 '20 at 17:27
  • [Why is global state so evil?](https://softwareengineering.stackexchange.com/search?tab=votes&q=global%20variables%20is%3aquestion) – Barmar Jan 23 '20 at 17:28
  • You could wrap it with a class and make those variables members of the class. Then you could have multiple instances without one stepping on the variables of another. – shanecandoit Jan 23 '20 at 17:29
  • The one sentence answer is actually contained in the question: "the value [...] from outside the scope of the nested function is changed." – Adam Smith Jan 23 '20 at 17:29

1 Answers1

1

To give a simple answer: because it's hard to read. For example:

I have three functions:

def a():
    A *= 2

def b():
     A += 7

 def C():
     A = 0

Also, A is 2 originally

Now, imagine these functions are split up over multiple files. One day you want to do a task A times but A has a differentvalue than you expect! Now, how would you ever figure out why A has a different value? Where do you start debugging?

If instead all these functions needed A as input and returned it as well, it would instantly be clear where yourvariables are used and whenthey change, much easier to debug!

Nathan
  • 3,558
  • 1
  • 18
  • 38