Why do we have to do this:
global x
x = "Hello World!"
When this is more readable:
global x = "Hello World"
Why is this, is there a reason behind it?
Why do we have to do this:
global x
x = "Hello World!"
When this is more readable:
global x = "Hello World"
Why is this, is there a reason behind it?
The goal of Python is to be as readable as possible. To reach this goal the user must be forced act in a clear defined way - e.g. you must use exactly four spaces. And just like this it defines that the global
keyword is a simple statment. This means:
A simple statement is comprised within a single logical line. Simple Statements
And
Programmer’s note: the global is a directive to the parser. It applies only to code parsed at the same time as the global statement. The global statement
If you would write this:
global x = 5
You would have two logical operations:
in one line. Also it would seem like the global
only applies to the current line, and not to the whole code block.
TL;TR
It's to force the user to write better readably code, which is splitted to single logical operations.
The document writes that
Names listed in a
global
statement must not be used in the same code block textually preceding that global statement.CPython implementation detail: The current implementation does not enforce the latter two restrictions, but programs should not abuse this freedom, as future implementations may enforce them or silently change the meaning of the program.
As for the readability question, I think the second one seems like a C statement. Also it not syntactically correct
I like to think it puts your focus squarely on the fact that you are using globals, always a questionable practice in software engineering. Python definitely isn't about representing a problem solution in the most compact way. Next you'll be saying that we should only indent one space, or use tabs! ;-)