Python Global Variable – How to reach them?

In python there is no scope for variables, however function definitions create their local versions as default and to edit global variable you need to declare it with a specific prefix.

global VAR1

Here are some examples

Non global variable case

>>> def edit_var():
...    VAR1=7
...
>>> VAR1 = 3
>>> VAR1
3
>>> edit_var()
>>> VAR1
3

Global variable case

>>> def edit_var():
...     global VAR1
...     VAR1 = 7
...
>>> VAR1 = 3
>>> VAR1
3
>>> edit_var()
>>> VAR1
7
>>>

Or with two different functions

>>> def edit_var():
...     VAR1 = 666
...
>>> def edit_global_var():
...     global VAR1
...     VAR1 = 1337
...
>>> VAR1 = 1
>>> VAR1
1
>>> edit_var()
>>> VAR1
1
>>> edit_global_var()
>>> VAR1
1337
>>> edit_var()
>>> VAR1
1337
>>>

In the last example we can see that edit_global_var() can reach and edit value of the VAR1.

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.