Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

globals
locals
function
python
communitycreator

What is the Python locals() function?

NDUKWE CHIDERA K.

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Introduction

In the Python programming language, there is a concept known as local scope. When a variable is defined in the local scope of a function or namespace, it can only be accessed within such a function/namespace.

What is the locals() function?

The Python locals() function, when called within a function/namespace, returns all the names that can be accessed within that function/namespace.

This return value is in the form of a dictionary. Therefore, the names can be accessed using the Python key() function.

Syntax

locals()

Parameter

This function takes no parameter. It only has to be called within a function or a namespace and it executes within the function or namespace’s scope.

Return value

This function returns the information contained in the local symbol table for that function/namespace.

A local symbol table is created by a compiler as a data structure which holds all information needed to execute a program in the local scope.

Code

# Python program to understand the locals() function
# here no local variable is present
def trial1():
print("Here no local variable is present : ", locals())
# here local variables are present
def trial2():
name = "Pluto"
print("These are the local variable here : ", locals())
# call the functions
trial1()
trial2()
An example of the locals() function

Explanation

In the above code, two functions trial1() and trial2() were defined. trial2() was given some local variables and trial1() was given none. Upon calling the locals() function, there was no variable to be returned in trial1(), while those present in trial2() were returned.

RELATED TAGS

globals
locals
function
python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Keep Exploring