global keyword allows to modify the variable which is out of current scope.
In : bar = 1 In : def foo(): ....: global bar ....: bar = 2 ....: In : bar Out: 1 In : foo() In : bar Out: 2
In the above example,
bar was declared before
foo function. global
bar refers to the
bar variablewhich is outside the
foo scope. After
bar value was modified inside
foo. The value ismodified globally.
What happens when
bar becomes function inside
In : bar = None In : def foo(): ....: global bar ....: def bar(): ....: return 'I am bar' ....: In : bar In : foo() In : bar Out: <function __main__.bar>
bar was variable outside
foo’s scope. Now creating a new function
bar global variable.
This may not be obvious at first step, then you realize function can be aliased to variable.
- Parameterize Python Tests
- “Don’t touch your face” - Neural Network will warn you
- Capture all browser HTTP[s] calls to load a web page
- How long do Python Postgres tools take to load data?
- Debugging Python multiprocessing program with strace
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.