Open In App

Python | locals() function

Last Updated : 16 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Python locals() function returns the dictionary of the current local symbol table. We use it to access the local symbol table in Python.

  • Symbol table: It is a data structure created by a compiler that is used to store all information needed to execute a program.
  • Local symbol Table: This symbol table stores all information needed for the local scope of the program and this information is accessed using the Python built-in function locals().

Python locals() Function Syntax

We can access the local symbol table in Python by using locals() function.

Syntax: locals()

Parameters: This function does not takes any input parameter. 

Return Type : This returns the information stored in local symbol table.

locals() Function in Python Examples

Python locals() works insides a local scope

In this example, we are using the locals() function to show how it works inside a local scope. In demo1, no local variables are defined, so calling locals() returns an empty dictionary. In demo2, a local variable named name is defined, and calling locals() returns a dictionary containing the “name” variable with the value “Ankit.”

Python3




# Python program to understand about locals
# here no local variable is present
 
def demo1():
    print("Here no local variable  is present : ", locals())
 
# here local variables are present
def demo2():
    name = "Ankit"
    print("Here local variables are present : ", locals())
 
# driver code
demo1()
demo2()


Output

Here no local variable  is present :  {}
Here local variables are present :  {'name': 'Ankit'}





Updating using locals()

Unlike globals() this function can not modify the data of the local symbol table. We can only access the local symbol table in Python by using it. The below program explains it clearly. 

Python3




# Python program to understand about locals
# here no local variable is present
 
def demo1():
    print("Here no local variable  is present : ", locals())
 
# here local variables are present
def demo2():
    name = "Ankit"
    print("Here local variables are present : ", locals())
    print("Before updating name is  : ", name)
 
    # trying to change name value
    locals()['name'] = "Sri Ram"
 
    print("after updating name is : ", name)
 
# driver code
demo1()
demo2()


Output

Here no local variable  is present :  {}
Here local variables are present :  {'name': 'Ankit'}
Before updating name is  :  Ankit
after updating name is :  Ankit





locals() for global environment

The local symbol table is the same as the global symbol table in the case of the global environment. 

Python3




# Python program to understand about locals
 
# data using locals
print("This is using locals() : ", locals())
 
# data using globals
print("This is using globals() : ", globals())


Output

This is using locals() :  {‘__name__’: ‘__main__’, ‘__doc__’: ‘Automatically created module for IPython interactive environment’, ‘__package__’: None, ‘__loader__’: None, ‘__spec__’: None, ‘__builtin__’: <module ‘builtins’ (built-in)>, ‘__builtins__’: <module ‘builtins’ (built-in)>, ‘_ih’: [”, ‘import multiprocessing\nfrom bs4 import BeautifulSoup\nfrom queue import Queue, Empty\nfrom concurrent.futures import ThreadPoolExecutor\nfrom urllib.parse import urljoin, urlparse\nimport requests\n\n\nclass MultiThreadedCrawler:\n\n    def __init__(self, seed_url):\n        self.seed_url = seed_url\n        self.root_url = \'{}://{}\’.format(urlparse(self.seed_url).scheme,\n                                         urlparse(self.seed_url).netloc)\n        self.pool = ThreadPoolExecutor(max_workers=5)\n        self.scraped_pages = set([])\n        self.crawl_queue = Queue()\n        self.crawl_queu

Python locals VS global functions

The python globals() function in Python returns the dictionary of the current global symbol table. It is used to retrieve a dictionary that represents the current global symbol table.

Python globals() Syntax

Syntax: globals()

Parameters: No parameters required.

globals() in Python

In this example, we are showing how globals() can be used to access and change global variables from within a function.

Python3




# Python3 program to demonstrate global() function
 
# global variable
a = 5
 
def func():
    c = 10
    d = c + a
     
    # Calling globals()
    globals()['a'] = d
    print (d)
     
# Driver Code   
func()


Output

15





Python locals() function in Python returns the dictionary of the current local symbol table.

Python3




locals()


Output

{‘__name__’: ‘__main__’,

 ‘__doc__’: ‘Automatically created module for IPython interactive environment’,

 ‘__package__’: None,

 ‘__loader__’: None,

 ‘__spec__’: None,

 ‘__builtin__’: <module ‘builtins’ (built-in)>,

 ‘__builtins__’: <module ‘builtins’ (built-in)>,

 ‘_ih’: [”,

  ‘# Python program to demonstrate the use of\n# len() method  \n\n# Length of below string is 5\nstring = “geeks” \nprint(len(string))\n\n# Length of below string is 15\nstring = “geeks for geeks” \nprint(len(string))’,

  ‘# Python program to demonstrate the use of\n# len() method  \n\n# L

Frequently Asked Questions 

What are locals in Python?

The locals() function in Python retrieves a dictionary containing all the information stored in the local symbol table. The local symbol table is generated by the compiler and holds the necessary information for the execution of a program.

What are local variables in Python?

Local variables in Python are those specifically defined within a block of code, such as within a function. These variables have a limited scope and are accessible only within the confines of that block; attempting to use them outside of it will result in an error. To illustrate, a variable declared within a function is termed a local variable, and its scope is restricted to that particular function.

What are globals in Python?

Global variables in Python are accessible throughout the entire program, having been defined outside any specific function block. Their scope is considered global, allowing them to be utilized across different parts of the code. The globals() function facilitates access to information stored within the global symbol table. This table acts as a data structure containing essential details pertaining to the program’s global scope, playing a vital role in the program’s execution.

Does Python have local variables?

Yes, Python does have local variables. Local variables are variables that are defined within a specific block of code, such as inside a function or a loop. These variables have a limited scope and are only accessible within the block in which they are defined. Once the block is exited, the local variables are no longer available.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads