6 Examples to Demystify Python locals() Function

Introduction

In python, we have discussed many concepts and conversions. But sometimes, we come to a situation where we need to return the dictionary according to the current local symbol table. In this tutorial, we will be discussing the concept of the python locals() function, which is used to updates and returns a dictionary of the current local symbol table.

What is locals() function in Python?

Python locals() function is an in-built function used to update and return a dictionary of the current local symbol table. It is mostly used for debugging purposes. With the help of this function, We can check what variables are present in the local scope and their values. The local scope is within the function, within the class, etc.

Symbol Table: A symbol table is a type of data structure maintained or created by a compiler used to store all necessary information about the program. These include all the variable names, methods, classes, etc.

Local Symbol Table: The table is used to store all the information needed to the local scope of the program, and this information can be accessed using the built-in function locals().

Syntax

locals()

Parameters

It does not take any parameter.

Return value

It returns the dictionary associated with the current local symbol table.

Examples of locals() function in Python

Here, we will be discussing all the examples of the built in locals() function in python:

1. Using locals() function in Python

In this example, we will try to print directly the locals() function with the help of the print function in python. locals() function will directly paste the Local Symbol Table information on the console, on that scope where locals() was called from! Let us look at the example for understanding the concept in detail.

#print() function and locals() function
print(locals())

Output:

Using locals() function in Python

Explanation:

  • Here, we will directly print the given function with the help of the print function.
  • locals() function will directly paste the Local Symbol Table information on the console, on that scope where locals() was called from!
  • Hence, we obtain the required dictionary.

2. Using Python locals() function inside local scope

In this example, we will be using the function inside the local scope of the program. In this, we will be creating the two functions and then call the locals() function. Let us look at the example for understanding the concept in detail.

def NotPresent():
    return locals()

def present():
    Present = True
    return locals()

print('NotPresent of locals:', NotPresent())
print('Present of locals:', present())

Output:

locals() function inside local scope

Explanation:

  • Firstly, we will make two functions i.e NotPresent() and present().
  • Inside, the Notpresent() function we will directly return the values of locals() function.
  • Inside, the present() function we will put present equals to True and return locals() function.
  • Hence, we will see the output of both the function made.

3. Updating dictionary values by Python locals() Function

In this example, we will be updating locals() dictionary values. Let us look at the example for understanding the concept in detail.

def localsPre():
    str = True
    print(str)
    locals()['str'] = False;
    print(str)

localsPre()

Output:

 Updating dictionary values

Explanation:

  • Firstly, we will make the localsPre() function in the code.
  • Then, we will define that function with str equals to True and print the value of str.
  • After that, we will try to update locals() dictionary values by putting str equals to False.
  • At last, we will see the output.
  • Hence, you can see the output.

4. Python locals() function for global environment

In this example, we will be printing both the locals() function and the globals() function. Through this, we will be telling you that the local symbol table is the same as the global symbol table in the case of the global environment. Let us look at the example for understanding the concept in detail.

print("This is using locals() : ", locals())
print("\n")
print("This is using globals() : ", globals())

Output:

locals() function for global environment

Explanation:

  • Firstly, we will print the locals() function.
  • Then, we will print a new line.
  • At last, we will print the globals() function.
  • Hence, we can see that the local symbol table is the same as the global symbol table in the case of the global environment.

5. Using locals() function inside a class

In this example, we will be using the locals() function inside the class. We will declare the class name with python and inside the class, we will take a variable num which will be having the value 100. Then, we will call the locals() function and see the output. Let us look at the example for understanding the concept in detail.

class python:
    num = 100
    print('\nlocals() value inside class\n', locals())

Output:

inside a class

Explanation:

  • Firstly, we will declare a class with name python.
  • Inside the class, we will declare a variable num which is equal to 100.
  • Then, we will call the locals() function inside the class only.
  • At last, we will be seeing the output.

6. Using locals() with list comprehension

In this example, we will be using the function in a list comprehension. But, the function has its own set of local variables as it is in a separate scope – thus yielding this unexpected behaviour. Let us look at the example for understanding the concept in detail.

lang = ["python", "java", "c++", "ruby", "go"]

newlist = [locals().get(var) for var in lang]

print(newlist)

Output:

locals() with list comprehension

Explanation:

  • Firstly, we will declare the list as lang with some languages in computer science.
  • We will then be applying the locals() function in the list comprehension and storing the output in the newlist.
  • At last, we are trying to print the new list.
  • Hence, we can see that the output shows unexpected behavior as the list comprehension has its own set of local variables.

Difference between locals(), globals() and vars() function

locals() function

Python locals() function is an in-built function used to update and return a current local symbol table dictionary.

globals() function

Python globals() function is an in-built function used to update and return a dictionary of the current global symbol table.

To get the in-depth knowledge about the python globals() function click here.

vars() function

Python vars() function is an in-built function used to return a dictionary of the current namespace or the dictionary of argument. The main difference between vars() and locals() is that vars() can take an argument and return a dictionary for the requested object.

To get the in-depth knowledge about the python vars() function click here.

If we write the locals() function and globals() function in the global environment, they will result in the same output. So, we will be taking an example with the help of function.

def func():
    num = 31
    print ("Locals : ", locals())
    print ("Vars : ", vars())
    print ("Globals : ", globals())
func()

Output:

Calling locals() in a function not intuitive?

In this example, we will see that calling a function is not intuitive. I thought the output would be like locals_1 would contain var; locals_2 would contain var and locals_1; and locals_3 would contain var, locals_1, and locals_2. But, the output is something else when I run the code. Let us look at the example for understanding the concept in detail.

def func():
  var = 'var!'
  locals_1 = locals()
  locals_2 = locals()
  locals_3 = locals()
  return locals_1, locals_2, locals_3

# func is called ...
locals_1, locals_2, locals_3 = func()

# display results ...
print ('locals_1:', locals_1)
print ('locals_2:', locals_2)
print ('locals_3:', locals_3)

Output:

How to find keys in locals() python?

We can find keys in locals() python with the given code. As locals() returns a dictionary, you can use keys() to get all keys.

print(locals().keys())

Output:

Conclusion

In this tutorial, we have discussed the concept of the built-in locals() function in python. We have seen what the locals() function, symbol table, and local symbol table is. Then, we have explained to you the syntax, parameter, and return value of the function. At last, we have explained the concept in detail with the help of different examples. All the examples are explained in detail with the help of examples. You can use any of the functions according to your choice and your requirement in the program.

However, if you have any doubts or questions, do let me know in the comment section below. I will try to help you as soon as possible.

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments