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



The Python built-in functions, dir(), globals(), and locals are used to provide insights into the objects, variables, and identifiers present in various scopes.

They might look similar, but each function serves a different purpose and behaves differently depending on where and how it is used.

In this article, we will discuss the difference between the dir(), globals(), and locals() in Python.

Python dir() Function

The Python dir() function is used to list the names in the current local scope or the attributes of an object. If no argument is passed, it returns the list of names in the current local scope. Following is the syntax of the Python dir() function -

dir(object)

Example

Let's look at the following example, where we are going to use the dir() function without arguments.

a = 11
def demo():
    b = 12
    print(dir())
demo()

The output of the above program is as follows -

['b']

Python globals() Function

The Python globals() function is used to return the dictionary representing the current global symbol table. It includes all the global variables and functions defined at the module level. Following is the syntax of the Python globals() function -

globals()  

Example

In the following example, we are going to use the globals() function to access the global variables.

a = 112
b = "TutorialsPoint"
print(globals()['a'])
print(globals()['b'])

The following is the output of the above program -

112
TutorialsPoint

Python locals() Function

The Python locals() function is used to return the dictionary representing the current local symbol table. When this is invoked inside the function, it reflects the function's local namespace. Following is the syntax of Python the locals() function -

locals()

Example

Consider the following example, where we are going to use the locals() inside a function to inspect all the local variables.

def demo():
    a = "Welcome"
    b = "Hi"
    print(locals())
demo()

The following is the output of the above program -

{'a': 'Welcome', 'b': 'Hi'}
Updated on: 2025-06-17T17:36:01+05:30

707 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements