The globals () function in Python

The globals () function in Python returns a dictionary containing the variables defined in the global namespace.

The globals () function in Python returns a dictionary containing the variables defined in the global namespace. When globals () is called from a function or method, it returns the dictionary representing the global namespace of the module where the function or method is defined, not from where it was called. So what is the syntax of globals () function, what parameters does it have and how to use it? Invites you to read the track.

Python globals () syntax in Python

 globals() 

There are no parameters and arguments in the function.

Value returned from globals

The globals () function returns the dictionary representing the global namespace of the module where the function or method is defined, not from where it was called.

Example: How does the globals () function work?

 globals() 

Run the program, the result is:

 {'In': ['', 'globals()'], 
'Out': {},
'_': '',
'__': '',
'___': '',
'__builtin__': , '__builtin__': ,
'__builtins__': , '__builtins__': ,
'__name__': '__main__',
'_dh': ['/tmp/tmpx_16f0vp'],
'_i': '',
'_i1': 'globals()',
'_ih': ['', 'globals()'],
'_ii': '',
'_iii': '',
'_oh': {},
'_sh': , '_sh': ,
'exit': ,
'get_ipython': >,
'quit': }

Example 2: Modifying global variables with global ()

 tuoi = 23 

globals()['tuoi'] = 25
print('So tuoi la:', tuoi)

Running the program results in:

 So tuoi la: 25 

The global namespace stores all global variables, ie in this example, the value of the variable can be changed using the globals () function. The returned dictionary is accessed and changed to 25.

Previous lesson: Getattr () function in Python

Next lesson: Python locals () function

Update 25 May 2019
Category

System

Mac OS X

Hardware

Game

Tech info

Technology

Science

Life

Application

Electric

Program

Mobile