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
You should read it
- Int () function in Python
- The function id () in Python
- Max () function in Python
- Zip () function in Python
- The function dir () in Python
- The ord () function in Python
- The iter () function in Python
- Exec () function in Python
- The function set () in Python
- The map () function in Python
- Getattr () function in Python
- Isinstance () function in Python
Maybe you are interested
Close-up of a diver's encounter with anaconda and piranha in the Brazilian river The woman caught a giant tuna weighing 411 kg 11 fastest swimming fish in the world What does the 'super slow' 7680fps movie recording feature on the Mate 30 Pro do? Hitman Sniper famous game is being free on iOS and Android How to create slow motion videos on Android?