6

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?

  • 7
    Python doesn't have any other variable modifiers, but does have other statements; this therefore keeps the grammar simpler. As to which is more readable, that's inevitably a matter of opinion. – jonrsharpe Jun 07 '16 at 22:22
  • It would become less readable with more variables. for example: `global x = "Hello world", y ="What's up world", z ="Goodbye world"` it gets a little full. – BradTheBrutalitist Jun 07 '16 at 22:28
  • I don't think you are going to get any definitive answer bar asking Guido or some of the devs. – Padraic Cunningham Jun 08 '16 at 00:24

3 Answers3

1

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:

  1. Interpreter please use the global x not a local one
  2. Assign 5 to x

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.

falx
  • 139
  • 3
  • 13
  • Falx, thank you for the time and effort you took to answer my question, I have a better understanding now, +1. –  Jun 08 '16 at 12:02
0

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

gdlmx
  • 6,479
  • 1
  • 21
  • 39
  • Gdlmx, thank you for the time and effort you took to answer my question, +1. –  Jun 08 '16 at 12:03
-1

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! ;-)

holdenweb
  • 33,305
  • 7
  • 57
  • 77
  • Holdenweb, thank you for the time and effort you took to answer my question, +1. –  Jun 08 '16 at 12:02