Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any use for a top-level global variable declaration?

In Python, the global declaration is used inside function definitions to specify that assigning the variable will create/update a global variable, rather than the default local variable.

Python also allows the global statement outside of function definitions. This doesn't cause an error, which leads many beginners to misuse it by writing the top-level declaration once instead of putting it in each function that needs it.

It seems like this should be a syntax error, like using return outside a function or break outside a loop. Do these declarations serve any purpose, which would explain why it's allowed?

like image 653
Barmar Avatar asked Oct 29 '25 20:10

Barmar


1 Answers

they just are not an error, and do no harm, Remember that Python was created as a permissive first language, and remained so for over 2 decades. In recent years, this feelings had shifted among some language user demographics, which prefer explicitly settling for a more restrictive use of the language.

It makes no sense to directly disallow a harmless permitted usage of global or other kwyeword though. For those who prefer more restrictive practices, I am certain that linters and other tooling will warn about a misplaced global, or if not, that could be filled as a feature requested in those tools.

But thinking about restricting it in core Python? What for? And what else should be restricted? Should all no-op expressions be simply transformed into syntax errors? (like, just mentioning a variable in a line by itself?). At what point that language would not be Python anymore?

And finally, but not least important: an out-of-scope global is a clear reminder for any human reading the code that the following variable is intended to be used as a global - so it does has semantical meaning, if not syntactic - and maybe the correct approach would be to do the reverse: to include declaring a top-level global as a good practice in type-hinted code, since the goal there is to have the maximum information (both human and machine readable) about an entity at the point it is first mentioned in the code.

like image 64
jsbueno Avatar answered Oct 31 '25 12:10

jsbueno