What is the difference between dir(), globals() and locals() functions in Python?

PythonServer Side ProgrammingProgramming

locals() returns you a dictionary of variables declared in the local scope while globals() returns you a dictionary of variables declared in the global scope. At global scope, both locals() and globals() return the same dictionary to global namespace. To notice the difference between the two functions, you can call them from within a function. For example,

def fun():
    var = 123
    print "Locals: ", locals()
    print "Vars: ", vars()
    print "Globals: ", globals()

This will give the output:

Locals:  {'var': 123}
Globals:  {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', 'fun': <function fun at 0x00000000
037E3DD8>, '__doc__': None, '__package__': None}

vars() returns either a dictionary of the current namespace (if called with no argument) or the dictionary of the argument. The main difference between locals() and vars() is that vars() can also take an argument and return dictionary for requested object. For example, if you want the attributes of an object in a dict, you can pass that object and get the attribute dict for that instance.

vars() function for object is similar to __dict__ property for the same object. __dict__ returns all defined attribute for object. For example,

class A():
    def __init__(self, id):
        self.id = id
a = A(1)
print "__dict__: ", a.__dict__
print "vars(a): ", vars(a)

This will give the output:

__dict__:  {'id': 1}
vars(a):  {'id': 1}
Published on 19-Dec-2017 13:19:39