Methods and Functions

Python globals()

The Python globals function is a built-in function used for updating and returning a dictionary containing the current global symbol table. The inbuilt Python globals() function allows us to get a list of all global variables and their values in the specific code throughout the program.

Python globals

The python globals function is a built-in function that is used to modify and return a dictionary and its values of the current global symbol table. A symbol table is a data structure maintained and constructed by the Python compiler that contains all of the essential information about each identifier found in the source code of the program.

This data pertains to an identifier’s type, value, scope level, and its position (also called symbol). Variable names, methods, classes, and so on are other examples. A dictionary returned by the globals() function stores the collection of symbols available to the interpreter at the Python interactive interface.

There are 2 kinds of symbol tables:

  • Local symbol table
  • Global symbol table

Local symbol table

The local symbol table maintains all information relating to the program’s local scope and is accessed in Python via the locals() function. The local scope could be within a function, a class, or anything else.

Global symbol table

The global symbol table is used to hold all of the information required for the program’s global scope, which may be accessed using the built-in Python globals() method. All functions and variables that are not associated with any class or function are included in the global scope.

Python globals() function

Functions and variables that are not connected with a specific class or function are stored globally. It is usually used for debugging purposes to see what items are truly in the global scope.

globals() python Syntax

The Python globals() function follows the below-mentioned syntax:

python globals Parameters

This function does not accept any parameters. If you pass any parameters to the globals() function, the Python interpreter will throw a TypeError.

Return value from globals()

Python’s globals() function is responsible for returning a dictionary of the current global symbol table.

Example 1: How globals python method works

Example

                    

# Python program to illustrate globals()
# prints current global symbol table
print(globals())
print('')

# declaring global variables
a = 10
b = 100
c = 1000

# prints current global symbol table
print(globals())

Output

                    

{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': 
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>}


{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': 
<class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
 '__builtins__': <module 'builtins' (built-in)>, 'a': 10, 'b': 100, 'c': 1000}

Explanation

In the first globals() print statement, we get a dictionary containing all the things in scope in the global namespace. In the second globals() print statement we get the global namespaces along with the newly declared variables ‘a’, ‘b’, ‘c’ and their values.

Example 2: Modify global variable using globals in python

Using the Python globals() dictionary, we can modify or change the global variables. The symbol table is also modified as a result of the new value. Python contains a global keyword as well. It enables the usage and modification of a globally declared variable within a function, ensuring that the changes are reflected worldwide as well.

Example

                    

# Python program to illustrate globals()
car_brand = 'Jaguar'
print('Old Car:', car_brand)

globals()['car_brand'] = 'Ferrari'
print('New Car:', car_brand)
print('')

name = 'Rocky'
def Name():
    name = globals()['name']
    name = 'Charlie'
    print ('global variable myname inside function:', name)
    return
Name()
print ('global variable myname in global scope:', name)

Output

                    

Old Car: Jaguar
New Car: Ferrari

global variable myname inside function: Charlie
global variable myname in global scope: Rocky

FAQs on Python globals

Q1. What does globals mean in Python?

A global variable in computer programming is a variable with global scope, which means it is visible and accessible throughout the program’s lifetime. In the program, a Global Variable is a variable defined outside of the subroutine or function.

Python’s in-built globals() function allows us to get a list of all global variables and their values in the specific code throughout the program. We can then use this function to modify and update the global variables.

Q2. What are symbol tables in Python?

A symbol table is a data structure maintained and constructed by the Python compiler that contains all of the essential information about each identifier found in the source code of the program. This data pertains to an identifier’s type, value, scope level, and its position (also called symbol). Variable names, methods, classes, and so on are other examples. A dictionary returned by the globals() function stores the collection of symbols available to the interpreter at the Python interactive interface.

There are 2 kinds of symbol tables:

  • Local symbol table – Maintains information regarding the program’s local scope.
  • Global symbol table – Maintains information regarding the program’s global scope.

Q3. What is locals() in Python?

Just like the Python globals() function, the Python’s locals() method is used to update and return the current local symbol table dictionary.

Syntax:

Example

                    

def show_locals():
    val = 20
    print('Globals:', globals())
    print(40*'-')
    print('Locals:', locals())

show_locals()

Output

                    

Globals: {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, '__annotations__': {},
'__builtins__': <module 'builtins' (built-in)>, 'show_locals': }
----------------------------------------
Locals: {'val': 20}

Here we can see that we have defined a variable inside a function, which creates a local scope for the variable. Hence, when we print the locals(), we only get to see the local scope of the function ‘show_locals()’.

Q4. Difference between locals() and globals in Python?

  • Python globals() – The globals() method returns a dictionary containing all global variables and their values. It always returns the module namespace dictionary.
  • Python locals() – Python locals() provide the same function as globals(), but for methods. Within a method, we call locals(). locals() always returns a dictionary containing information about the current namespace.

If we code the Python locals() and globals() functions in the global environment, we will get the same result. As a result, we shall use a function in the below example to understand the difference between globals and locals.

Example

                    

num = 10

def myfunc():
    num = 20
    print('Locals:', locals())
    print('Globals:', globals())
myfunc()

Output

                    

Locals: {'num': 20}
Globals: {'__name__': '__main__', '__doc__': None, '__package__': None, 
'__loader__': <class '_frozen_importlib.BuiltinImporter'>, '__spec__': None, 
'__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, 'num': 10, 
'myfunc': }

Share with friends

Customize your course in 30 seconds

Which class are you in?
5th
6th
7th
8th
9th
10th
11th
12th
Get ready for all-new Live Classes!
Now learn Live with India's best teachers. Join courses with the best schedule and enjoy fun and interactive classes.
tutor
tutor
Ashhar Firdausi
IIT Roorkee
Biology
tutor
tutor
Dr. Nazma Shaik
VTU
Chemistry
tutor
tutor
Gaurav Tiwari
APJAKTU
Physics
Get Started

Leave a Reply

Your email address will not be published. Required fields are marked *

Download the App

Watch lectures, practise questions and take tests on the go.

Customize your course in 30 seconds

No thanks.