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.
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.
locals()
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.
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.
# Python program to understand the locals() function# here no local variable is presentdef trial1():print("Here no local variable is present : ", locals())# here local variables are presentdef trial2():name = "Pluto"print("These are the local variable here : ", locals())# call the functionstrial1()trial2()
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.