.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "auto_examples/basics/global_vs_local.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note Click :ref:`here ` to download the full example code or to run this example in your browser via Binder .. rst-class:: sphx-glr-example-title .. _sphx_glr_auto_examples_basics_global_vs_local.py: ====================== 1.14 global vs local ====================== .. GENERATED FROM PYTHON SOURCE LINES 7-10 It is very important to understand the difference between global scope and local scope of a variable/object in python. A variable defined outside a function has global scope while a variable defined inside a function has local scope. .. GENERATED FROM PYTHON SOURCE LINES 12-16 .. code-block:: default var = 1 def foo(): return .. GENERATED FROM PYTHON SOURCE LINES 17-19 Above the variable ``var`` has global scope. We can access it from anywhere in the script. .. GENERATED FROM PYTHON SOURCE LINES 22-26 .. code-block:: default def foo(): var1 = 1 return .. GENERATED FROM PYTHON SOURCE LINES 27-31 The variable ``var1`` has local scope. We can access, use and modify it only insdie the function ``foo``. We can not access it from outside the function ``foo``. If we try to access it from outside the function, python will give us an error. Hence the variable ``var1`` has local scope. .. GENERATED FROM PYTHON SOURCE LINES 33-36 If a variable is defined outside the function and a variable with same name is defined and(or) being modified inside a function, then that definition/modification inside the function will have no effect on the variable outside the function. .. GENERATED FROM PYTHON SOURCE LINES 38-50 .. code-block:: default var = 1 def foo(n): var = n print(var, 'inside foo') return foo(10) print(var, 'outside foo') .. rst-class:: sphx-glr-script-out .. code-block:: none 10 inside foo 1 outside foo .. GENERATED FROM PYTHON SOURCE LINES 51-54 `var` inside the `foo` is different than the `var` outside the `foo`. If we try to modify the value of a variable (with some exceptions) which is defined only outside the function, it will result in error. .. GENERATED FROM PYTHON SOURCE LINES 56-64 .. code-block:: default var = 1 def foo(n): print(n) var = var + n return var .. GENERATED FROM PYTHON SOURCE LINES 65-66 uncomment follwoing line .. GENERATED FROM PYTHON SOURCE LINES 66-69 .. code-block:: default # foo(10) # UnboundLocalError .. GENERATED FROM PYTHON SOURCE LINES 70-75 Read and try to make sense of the error message as understanding error messages is one of the best ways to master a programming language. So the variable `var` which is defined outside `foo` can not be accessed (actually it can be accessed but not changed/reassigned, discussion follows) inside `foo`. If we want to do so, we need to use the keyword ``global``. .. GENERATED FROM PYTHON SOURCE LINES 77-89 .. code-block:: default var = 1 def foo(n): global var print(n) var = var + n return var foo(10) .. rst-class:: sphx-glr-script-out .. code-block:: none 10 11 .. GENERATED FROM PYTHON SOURCE LINES 90-94 By making use of ``global`` statement, we are saying that the variable `var` inside the function is same object as the variable `var` outside the function `foo`. Similarly if a variable is defined inside the function, we can not access that variable outside the function. .. GENERATED FROM PYTHON SOURCE LINES 96-103 .. code-block:: default def foo(n): var1 = n+2 return foo(10) .. GENERATED FROM PYTHON SOURCE LINES 104-109 .. code-block:: default # uncomment following line # print(var1) NameError .. GENERATED FROM PYTHON SOURCE LINES 110-115 variable `var1` is defined inside the function and is removed from memory as soon as the function execution finishes at `return` statement. (Why I used `var1` instead of `var` for this example?) If we want to access a variable -which is defined inside the function- outside the function, we have to make this variable global by making use of ``global`` statement. .. GENERATED FROM PYTHON SOURCE LINES 117-125 .. code-block:: default def foo(n): global var1 var1 = n+2 return foo(10) .. GENERATED FROM PYTHON SOURCE LINES 126-130 .. code-block:: default # uncomment following line # print(var1) .. GENERATED FROM PYTHON SOURCE LINES 131-132 when python finds a variable is local .. GENERATED FROM PYTHON SOURCE LINES 134-142 .. code-block:: default var = 1 def foo(n): print(var) foo(10) .. rst-class:: sphx-glr-script-out .. code-block:: none 1 .. GENERATED FROM PYTHON SOURCE LINES 143-145 The above code shows we are able to access/employ/use/read the value of variable `var` inside `foo` without making it `global`. .. GENERATED FROM PYTHON SOURCE LINES 147-154 .. code-block:: default var = 1 def foo(n): print(var) var = 0 .. GENERATED FROM PYTHON SOURCE LINES 155-159 .. code-block:: default # uncomment following line # foo(10) # UnboundLocalError .. GENERATED FROM PYTHON SOURCE LINES 160-168 So untill we defined the variable `var` inside `foo` by `var=0`, python did not create the local variable `var`. Until that point if we use/access the value of `var`, python will give us the value of `var` from outer scope. But as soon as we defined `var` inside the function `foo`, then python knows that this `var` is a local variable and is different than `var` outside the `foo`. Python then creates the local variable `var`. At this point python makes the variable `var`, **local**. (You can say, python forgets what `var` in outer scope is). As we tried to use `var` before declaring it global, hence the error message. .. GENERATED FROM PYTHON SOURCE LINES 170-184 .. code-block:: default var = 1 def foo(n): global var var = n # modifying global copy of var def print_var(): print(var) # prints global value of var print(var) foo(10) print_var() .. rst-class:: sphx-glr-script-out .. code-block:: none 1 10 .. GENERATED FROM PYTHON SOURCE LINES 185-189 **Takeaway:** We need to declare a variable as `global` in a function which assigns a value of it. If we want to ONLY USE a global variable in local scope, we can do this without declaring it global. However, this is error prone and should be avoided. For example, following code works but it is not recommended. .. GENERATED FROM PYTHON SOURCE LINES 189-196 .. code-block:: default var = 1 def foo(n): return n+var foo(10) .. rst-class:: sphx-glr-script-out .. code-block:: none 11 .. GENERATED FROM PYTHON SOURCE LINES 197-200 The above code works but it is not recommended. It is better to declare the variable as global if we want to use it in local scope. Or we can pass the variable as argument to the function. .. GENERATED FROM PYTHON SOURCE LINES 200-207 .. code-block:: default var = 1 def foo(n, var): return n+var foo(10, var) .. rst-class:: sphx-glr-script-out .. code-block:: none 11 .. GENERATED FROM PYTHON SOURCE LINES 208-214 The above code is better than the previous one. We are passing the variable `var` as argument to the function `foo`. However, the name of the variable `var` inside the function `foo` is same as the name of the variable `var` outside the function. This is also not recommended since it is error prone and many modern IDEs will raise warnings. We should use different names for variables in different scopes. The following code is better than the previous one. .. GENERATED FROM PYTHON SOURCE LINES 214-221 .. code-block:: default var = 1 def foo(n, var1): return n+var1 foo(10, var) .. rst-class:: sphx-glr-script-out .. code-block:: none 11 .. GENERATED FROM PYTHON SOURCE LINES 222-226 *alternative to global* ======================= If we want to share a variable between two functions, and the outer scope, we have to make use of ``global`` statement in both functions. .. GENERATED FROM PYTHON SOURCE LINES 228-245 .. code-block:: default var = 0 # The initial value of x, with global scope def foo2(): global var var = var + 5 def main(): global var # So we can change the value of var inside main print(var) # first check the var inside main var = 10 print(var) foo2() print(var) main() .. rst-class:: sphx-glr-script-out .. code-block:: none 0 10 15 .. GENERATED FROM PYTHON SOURCE LINES 246-249 We should normaly avoid sharing variables among different functions with the help of ``global``. The alternative to do this, is to make use of functions with ``return`` statement. The above code can be written as follows. .. GENERATED FROM PYTHON SOURCE LINES 251-264 .. code-block:: default def foo1(parameter): return parameter + 5 def main(var): print(var) var = 10 print(var) var = foo1(var) print(var) main(0) .. rst-class:: sphx-glr-script-out .. code-block:: none 0 10 15 .. GENERATED FROM PYTHON SOURCE LINES 265-269 existence of a vriable ======================= We have already created the variable `var` previously. Now the variable `var` exists in memory. We can print its value. .. GENERATED FROM PYTHON SOURCE LINES 271-274 .. code-block:: default print(var) .. rst-class:: sphx-glr-script-out .. code-block:: none 15 .. GENERATED FROM PYTHON SOURCE LINES 275-276 We can delete the variable from memory by making use of `del` statement. .. GENERATED FROM PYTHON SOURCE LINES 278-281 .. code-block:: default del var .. GENERATED FROM PYTHON SOURCE LINES 282-284 Now if we try to print the value of `var` again, python says it does not know what is `var`, since we removed it from memory. .. GENERATED FROM PYTHON SOURCE LINES 286-290 .. code-block:: default # uncomment following line # var # NameError .. GENERATED FROM PYTHON SOURCE LINES 291-293 If we try to delete a variable which does not exist in memory, python will raise an error. .. GENERATED FROM PYTHON SOURCE LINES 293-298 .. code-block:: default # uncomment following line # # del var # NameError .. GENERATED FROM PYTHON SOURCE LINES 299-301 If we want to safely remove/delete a variable, we can first check whether it is present in memory or not and delete it only if it is present as shown below. .. GENERATED FROM PYTHON SOURCE LINES 303-312 .. code-block:: default _all = locals().copy() _all.update(globals()) if 'var' in globals(): del var print('var removed') else: print('it was not in memory') .. rst-class:: sphx-glr-script-out .. code-block:: none it was not in memory .. GENERATED FROM PYTHON SOURCE LINES 313-315 We can create the variable `var` once again and try to remove it using the above method to validate it. .. GENERATED FROM PYTHON SOURCE LINES 317-321 .. code-block:: default var = 3 var .. rst-class:: sphx-glr-script-out .. code-block:: none 3 .. GENERATED FROM PYTHON SOURCE LINES 322-329 .. code-block:: default if 'var' in globals(): del var print('var removed') else: print('it was not in memory') .. rst-class:: sphx-glr-script-out .. code-block:: none var removed .. GENERATED FROM PYTHON SOURCE LINES 330-333 ``globals()`` returns a dictionary of all global variables while ``locals()`` returns a dictionary of all local variables. The names of variables are keys of these dictionaries and values of these variables are values of these keys in these dictionaries. .. GENERATED FROM PYTHON SOURCE LINES 335-341 .. code-block:: python for k,v in locals().items(): print(k)#, v) # not printing values for brevity .. GENERATED FROM PYTHON SOURCE LINES 344-349 .. code-block:: python for k,v in globals().items(): print(k) .. GENERATED FROM PYTHON SOURCE LINES 352-354 We can call a function by its string name With the help of ``globals()``` function. In this way we can call a method by its ``string`` name. .. GENERATED FROM PYTHON SOURCE LINES 356-364 .. code-block:: default def qatal(a): print(a + ' sanaullah') func_as_string = 'qatal' globals()[func_as_string]('rana') # qatal(). .. rst-class:: sphx-glr-script-out .. code-block:: none rana sanaullah .. GENERATED FROM PYTHON SOURCE LINES 365-366 ``globals()[func_as_string]('rana')`` is equivalent to ``qatal('rana')``. .. GENERATED FROM PYTHON SOURCE LINES 368-375 Normally global variables are considered bad see this [1]_ and this [2]_ . In python, by convention, global is used for constants and variables are seldom used as global. Technically in python there is no difference between variables and constants, however it is a convention to capitalize GLOBAL CONSTANTS and not global_variables. It is recommende that you explicitly declare global inside a function when you are using a global variable even though if it is not required. .. GENERATED FROM PYTHON SOURCE LINES 377-379 If there is a local variable with same name as global variable and we want to modify global variable, we can make use of ``globals()``. .. GENERATED FROM PYTHON SOURCE LINES 381-395 .. code-block:: default thug = 'showbaz' def commision(accused): thug = 'nawaz' print('internal thug: ', thug) globals()['thug'] = accused print('internal thug: ', thug) return print('global thug before: ', thug) commision('bajwa') print('global thug later:', thug) .. rst-class:: sphx-glr-script-out .. code-block:: none global thug before: showbaz internal thug: nawaz internal thug: nawaz global thug later: bajwa .. GENERATED FROM PYTHON SOURCE LINES 396-403 Mutable objects =============== Above, we saw that if we want to modify the value of a variable which is defined outside the function, we have to use the keyword `global`. However, this is not the case with mutable objects. Mutable objects can be modified without using the keyword `global`. We can change/modify the values of mutable objects such as that of dictionaries from inside the function without declaring them global. .. GENERATED FROM PYTHON SOURCE LINES 405-415 .. code-block:: default thug = {'name': ' '} def commision(thug_name): thug['name'] = thug_name print(thug) commision('showbaz') print(thug) .. rst-class:: sphx-glr-script-out .. code-block:: none {'name': ' '} {'name': 'showbaz'} .. GENERATED FROM PYTHON SOURCE LINES 416-425 .. code-block:: default thugs = ['musharaf', 'zardari'] def commision(accused): thugs.append(accused) commision('nawaz') thugs .. rst-class:: sphx-glr-script-out .. code-block:: none ['musharaf', 'zardari', 'nawaz'] .. GENERATED FROM PYTHON SOURCE LINES 426-435 .. code-block:: default thugs = set(thugs) def commision(accused): thugs.add(accused) commision('bajwa') thugs .. rst-class:: sphx-glr-script-out .. code-block:: none {'zardari', 'bajwa', 'nawaz', 'musharaf'} .. GENERATED FROM PYTHON SOURCE LINES 436-439 Although tuples are immutable, thus they can not be modified but they can contain mutable objects such as lists, thus we can change/modify such contents of tuples from inside the function without using the keyword `global`. .. GENERATED FROM PYTHON SOURCE LINES 441-451 .. code-block:: default thugs_tuple = (list(thugs),) def commision(accused): thugs_tuple[0].append(accused) print(thugs_tuple) commision('pervailz elahi') print(thugs_tuple) .. rst-class:: sphx-glr-script-out .. code-block:: none (['zardari', 'bajwa', 'nawaz', 'musharaf'],) (['zardari', 'bajwa', 'nawaz', 'musharaf', 'pervailz elahi'],) .. GENERATED FROM PYTHON SOURCE LINES 452-458 `thugs_tuple` is a tuple but its first element is a list. We have modified the list inside the tuple without using the keyword ``global``. What will happen if we do assignment to a global variable inside function/local scope. The variable inside the local scope will be newly created while the immutable object outside the function will remain same. .. GENERATED FROM PYTHON SOURCE LINES 460-472 .. code-block:: default thugs = ['musharaf', 'zardari'] def commision(accused): thugs = [accused] print(thugs, 'inside') return print(thugs, 'outside') commision('nawaz') print(thugs, 'outside') .. rst-class:: sphx-glr-script-out .. code-block:: none ['musharaf', 'zardari'] outside ['nawaz'] inside ['musharaf', 'zardari'] outside .. GENERATED FROM PYTHON SOURCE LINES 473-475 However, as said earlier, if we used the keyword ``global``, this will affect the variable from global scope. .. GENERATED FROM PYTHON SOURCE LINES 477-490 .. code-block:: default thugs = ['musharaf', 'zardari'] def commision(accused): global thugs thugs = [accused] print(thugs, 'inside') return print(thugs, 'outside') commision('nawaz') print(thugs, 'outside') .. rst-class:: sphx-glr-script-out .. code-block:: none ['musharaf', 'zardari'] outside ['nawaz'] inside ['nawaz'] outside .. GENERATED FROM PYTHON SOURCE LINES 491-492 In general: variables in python are local unless declared otherwise. .. GENERATED FROM PYTHON SOURCE LINES 494-497 Questions ========= Answer the following questions without running the code above them. .. GENERATED FROM PYTHON SOURCE LINES 497-502 .. code-block:: default def foo(): number = 2 return number .. GENERATED FROM PYTHON SOURCE LINES 503-509 **Question:** What value will be printed by the following code? .. code-block:: python foo() print(number) .. GENERATED FROM PYTHON SOURCE LINES 511-512 **Question:** Did you get any error in the above code? If yes, then explain the error? .. GENERATED FROM PYTHON SOURCE LINES 514-526 .. code-block:: default num = 1 def add_something(var): return var + num def multipy_something(var): return var * num a = add_something(5) b = multipy_something(a) .. GENERATED FROM PYTHON SOURCE LINES 527-528 **Question:** What will be the value of ``b`` in above code? .. GENERATED FROM PYTHON SOURCE LINES 531-543 .. code-block:: default num = 1 def add_something(var): return var + num def multipy_something(var): return var * num a = add_something(5) num = 12 b = multipy_something(a) .. GENERATED FROM PYTHON SOURCE LINES 544-545 **Question:** What will be the value of ``b`` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 547-561 .. code-block:: default num = 1 def add_something(var): num = 14 return var + num def multipy_something(var): return var * num a = add_something(5) num = 12 b = multipy_something(a) .. GENERATED FROM PYTHON SOURCE LINES 562-563 **Question:** What will be the value of ``b`` in above and why? .. GENERATED FROM PYTHON SOURCE LINES 565-578 .. code-block:: default num = 1 def add_something(var): global num num = 14 return var + num def multipy_something(var): return var * num a = add_something(5) b = multipy_something(a) .. GENERATED FROM PYTHON SOURCE LINES 579-580 **Question:** What will be the value of ``b`` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 582-594 .. code-block:: default num = 1 def add_something(var): global num num = 14 def multipy_something(var): return var * num add_something(5) b = multipy_something(12) .. GENERATED FROM PYTHON SOURCE LINES 595-596 **Question:** What will be the value of `b` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 598-613 .. code-block:: default num = 1 def add_something(var): global num num = 14 def multipy_something(var): num = 12 return var * num add_something(5) num = num + 92 multipy_something(12) .. rst-class:: sphx-glr-script-out .. code-block:: none 144 .. GENERATED FROM PYTHON SOURCE LINES 614-615 **Question:** What will be the value of ``num`` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 617-631 .. code-block:: default num = 1 def add_something(var): global num num = 14 def multipy_something(var): global num num = num * var add_something(5) num = num + 92 multipy_something(12) .. GENERATED FROM PYTHON SOURCE LINES 632-633 **Question:** What will be the value of ``num`` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 635-650 .. code-block:: default book = "black" def change_book1(): book = "white" return def change_book2(): global book book = book + " white" change_book1() book = book + " skin" change_book2() book = book + " masks" .. GENERATED FROM PYTHON SOURCE LINES 651-652 **Question:** What will be the value of `book` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 654-667 .. code-block:: default book = {'name': 'black skin white masks'} def add_info(): book['author'] = 'frantz fanon' return def change_info(): book['name'] = 'white skin black masks' return add_info() change_info() .. GENERATED FROM PYTHON SOURCE LINES 668-669 **Question:** What will be the value of ``book['name']`` in above code and why? .. GENERATED FROM PYTHON SOURCE LINES 671-673 .. [1] ``_ .. [2] ``_ .. rst-class:: sphx-glr-timing **Total running time of the script:** ( 0 minutes 0.014 seconds) .. _sphx_glr_download_auto_examples_basics_global_vs_local.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: binder-badge .. image:: images/binder_badge_logo.svg :target: https://mybinder.org/v2/gh/AtrCheema/python-seekho/master?urlpath=lab/tree/notebooks/auto_examples/basics/global_vs_local.ipynb :alt: Launch binder :width: 150 px .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: global_vs_local.py ` .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: global_vs_local.ipynb ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_