Reputation: 1574
So I have this code in Python, in which I defined some global
variables and used them in different parts
def compute_sigma(mellin, alpha_power, beta_power, input_path, qr_epsilon):
global tf
...
return taus, error_mellin, error_factorization
## first part
global tf
tf = ...
...
taus, error_mellin, error_factorization = compute_sigma(...)
sys.exit()
## second part
global tf ## where the warning is generated
tf = ...
...
taus, error_mellin, error_factorization = compute_sigma(...)
I was trying to execute first part by exiting the program at where the sys.exit()
is, but it seems like Python is not ignoring the code completely after sys.exit()
, it is showing the following warning message
verification.py:257: SyntaxWarning: name 'tf' is assigned to before global declaration
Line 257 is where the last global
definition is.
Is there a cleverer way of exiting the program? I tried os._exit ()
, exit()
and quit()
, none of them would work.
Also, please let me know if you need to reproduce the warning, I can make a toy function for you to test.
Thanks in advance!
Upvotes: 0
Views: 236
Reputation: 531055
TL;DR Don't use global
at the global level; it doesn't serve any purpose there, and it makes the parser mad.
global
only has real meaning inside a function, as it is an instruction to the compiler that the listed names refer to objects in the global scope, not local variables in the current scope.
It is a compiler directive, not really a true statement; you can't change the nature of a variable half-way through execution of the body of a function. A name is either local or global for the entire scope, regardless of where the global
statement might occur.
Still, even if you use global
at the global scope, it cannot occur after you have already assigned to the name, not so much for any semantic reason but there is no reason for the parser to treat it differently just because you (unnecessarily) used it in the global scope.
Upvotes: 2