Python Built-in Function locals():

The locals() is an inbuilt function in Python that returns the dictionary of the current local module namespace. In other words, this function returns all necessary information about the local scope of the program including the variable names, methods, etc. However, at the module level, locals() and globals() are the same dictionaries.

Signature

The signature for the locals() function is as shown below. Here, d is a dictionary that will be returned by this function.

d=locals()

Parameters and return type

  • This method doesn’t take any parameters.
  • However, it returns a dictionary containing the local scope of the program.

Python Built-in Function locals Examples:

Example 1: For example, let us initialize a variable, a list, and a set with some numbers. Thereafter, we will call the locals function. As a result, it returns the dictionary containing the name of a file, a package, cached data, loader along with the variable, list, and set.

#Initializing
a=5
l=[1,2,3]
s={11,22,33}
#Using locals and printing
print(locals())

Output

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7fb09591fd90>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'main.py', '__cached__': None, 'a': 5, 'l': [1, 2, 3], 's': {33, 11, 22}}

Example 2: In this example, we will take two functions a display and a star. Here, we will print a dictionary containing the local scope of a program. As we can see, there are no attributes in the display() function so, it prints an empty dictionary. Whereas, an attribute of the star() function is fetched and stored in the locals dictionary.

#Defining Function
def display():
    # Calling locals   
    print("Inside display ",locals())
def star():
    a=10
    b="Python"
    # Calling locals    
    print("Inside star ",locals())
#Function calling
display()
star()

Output

Inside display  {}
Inside star  {'a': 10, 'b': 'Python'}

Example 3: In this case, We will take a student class and a method inside a class. Now, let us initialize some attributes. Thereafter, we will create an instance of a class and make call to the function. As a result, it will print only the local workspace of the class.

#Defining class and function
class student:
   def func(self):
       name="John"
       branch="Computer"
       print(locals())
#Creating class instance and calling function
t=student()
t.func()

Output

{'self': <__main__.student object at 0x7fb788983880>, 'name': 'John', 'branch': 'Computer'}

Conclusion

The locals() function returns a dictionary consisting of locals namespace for the current program.

References

Happy Learning 🙂

Leave A Comment