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.
- Python Typing Koans
- Model Field - Django ORM Working - Part 2
- Structure - Django ORM Working - Part 1
- jut - render jupyter notebook in the terminal
- Five reasons to use Py.test
This work is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License.