Why should a variable be declared a global variable before it is assigned?

Why should we do this:

global x x = "Hello World!" 

If it is more readable:

 global x = "Hello World" 

Why is this, is there a reason for this?

+6
source share
3 answers

The goal of Python should be as readable as possible. To achieve this, the user must be forced to act in a clearly defined way - for example, you must use exactly four spaces. And in the same way, it determines that the global is a simple element. It means:

A simple instruction consists of one logical line. Simple statements

AND

Programmers note: global is a directive for the parser. It applies only to code analysis at the same time as the global expression. Global instruction

If you write this:

 global x = 5 

You will have two logical operations:

  • Interpreter, please use global x not local
  • Assign 5 to x

in one line. It would also look like global applies only to the current line, and not to the entire block of code.

TL TR

This forces the user to write code more readily, which is divided into separate logical operations.

+1
source

document writes that

The names listed in the global statement must not be used in the same code block that precedes this global statement.

Implementation details CPython: the current implementation does not apply the last two restrictions, but programs should not abuse this freedom, as future implementations may force them or silently change the meaning of the program.

Regarding the readability issue, I think the second one looks like the C operator. Also, this is not syntactically correct

0
source

I like to think that it puts your attention directly to the fact that you use global variables, always a dubious practice in software development. Python definitely does not present the problematic solution in the most compact way. Then you will say that we only need to retreat one place or use the tabs !; -)

-one
source

All Articles