
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
The globals(), locals() and reload() Functions in Python
The globals() and locals() are the Python built-in functions that are used to return the names in the global and local namespaces, depending on the location from where they are called. Whereas the reload() method is used to manage the Python modules.
The globals() Function
The globals() function in Python is used to get a dictionary representing the global namespace, containing all the global variables and their corresponding values in the current scope. If globals() is called from within a function, it will return all the names that can be accessed globally from that function.
Example
The following example demonstrates accessing the global variables within a function using the Python globals() function.
x = 10 def access_fun(): globalVar = globals()["x"] print(f"Accessing global variable: {globalVar}") access_fun()
This produces the following result:
Accessing global variable: 10
The locals() Function
The locals() function in Python is used to get a dictionary representing the local namespace, containing all the local variables, function, and their corresponding values. If locals() is called from within a function, it will return all the names that can be accessed locally from that function.
Example
This example shows how to use the locals() function to get the local variable names.
def local_fun(): a = 10 name = "TutorialsPoint" print("Local variables:", locals()) print("The local variables of the given functions are:") local_fun()
This produces the following result:
The local variables of the given functions are: Local variables: {'a': 10, 'name': 'TutorialsPoint'}
The reload() Function
When the module is imported into a script, the code in the top-level portion of a module is executed only once. Therefore, if you want to re-execute the top-level code in a module, you can use the reload() function. The reload() function is defined in importlib module, which is used to imports a previously imported module again.
Syntax
The syntax of the reload() function is this:
importlib.reload(module)
Where the module parameter is the module object to reload. This must be a module already imported and not the string containing the module name. For example, to reload the hello module, do the following:
reload(hello)