What is the difference between the global namespace and local namespace in Python?
The global and local namespaces in Python are both used for storing variables and functions, but they have some important differences.
- Global namespace is a namespace accessible throughout the entire program, including variables and functions defined outside of functions. On the other hand, local namespace is defined within a function and can only be accessed within that function.
- The global namespace is created at the start of a program and destroyed at the end, while the local namespace is created when a function is called and destroyed when the function finishes executing.
- When referencing a variable inside a function, Python will first look for it in the local namespace, and if not found, it will look in the global namespace. If still not found, it will raise a NameError.
- Inside a function, a variable can be declared as a global variable using the “global” keyword, allowing it to be modified within the function. However, outside of a function, the “global” keyword cannot be used to declare a local variable.
Overall, global namespaces and local namespaces differ in scope and lifetime, developers need to understand these differences in order to correctly use variables and functions.