Tuesday, May 5, 2015

Understading Scope of a function in python

Fire up your terminal or IDLE and type all these.

 In python functions create it's own name space or scope.
In the example below we are using two functions to illustrate that .
Each namespace is a different world.The variables defined in one function don't know about the variables defined in another function.
Python has builtins called globals() --> to display global variables.
locals() --> to display local variables.




>>> myvar="Hi i'm global"
>>> def foo():
...     a=1
...     print(locals())
... 

>>> def bar():
...     b=2
...     print(locals())
... 
>>> def my_func():
...     print("hi")
...     name="ajay"
...     place="India"
...     age='you cannot ask'
...     print(locals())
... 
>>> my_func()
hi
{'name': 'ajay', 'age': 'you cannot ask', 'place': 'India'}
>>> foo()
{'a': 1}
>>> bar()
{'b': 2}
>>> globals() #this may slightly vary for you
{'bar': , '__builtins__': , '__name__': '__main__', 'my_func': , '__package__': None, '__doc__': None, 'foo': , 'myvar': "Hi i'm global", '__spec__': None, '__loader__': }



Learn python for fun.The popular blog with questions and answers to the python.Solutions to facebookhackercup,codejam,codechef.The fun way to learn python with me.Building some cool apps.

No comments:

Post a Comment