top button
Flag Notify
    Connect to us
      Site Registration

Site Registration

What is the use of locals and globals function in python?

+2 votes
What is the use of locals and globals function in python?
posted Jan 27, 2015 by Gnanendra Reddy

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

1 Answer

+1 vote

These are builtin function i.e. locals() and globals()

locals(): Update and return a dictionary representing the current local symbol table. Free variables are returned by locals() when it is called in function blocks, but not in class blocks.


>>> def foo(arg): 1
...     x = 1
...     print locals()

>>> foo(7)        2
{'arg': 7, 'x': 1}

>>> foo('bar')    3
{'arg': 'bar', 'x': 1}

1   The function foo has two variables in its local namespace: arg, whose value is
    passed in to the function, and x, which is defined within the function.
2   locals returns a dictionary of name/value pairs. The keys of this dictionary are the 
    names of the variables as strings; the values of the dictionary are the actual values 
    of the variables. So calling foo with 7 prints the dictionary containing the function's 
    two local variables: arg (7) and x (1).
3   Remember, Python has dynamic typing, so you could just as easily pass a string 
    in for arg; the function (and the call to locals) would still work just as well. locals works 
    with all variables of all datatypes.

globals(): Return a dictionary representing the current global symbol table. This is always the dictionary of the current module (inside a function or method, this is the module where it is defined, not the module from which it is called).


if __name__ == "__main__":
    for k, v in globals().items():             
        print k, "=", v

Just so you don't get intimidated, remember that you've seen all this before. 
The globals function returns a dictionary, and you're iterating through the 
dictionary using the items method and multi-variable assignment. The only 
thing new here is the globals function.
answer Jan 27, 2015 by Salil Agrawal