How do I create or use a global variable inside a function?
How do I use a global variable that was defined in one function inside other functions?
Failing to use the global
keyword where appropriate often causes UnboundLocalError
. The precise rules for this are explained at UnboundLocalError on local variable when reassigned after first use. Generally, please close other questions as a duplicate of that question when an explanation is sought, and this question when someone simply needs to know the global
keyword.
Best Answer
You can use a global variable within other functions by declaring it as
global
within each function that assigns a value to it:Since it's unclear whether
globvar = 1
is creating a local variable or changing a global variable, Python defaults to creating a local variable, and makes you explicitly choose the other behavior with theglobal
keyword.See other answers if you want to share a global variable across modules.