๐น ๐๐๐ฆ๐๐ฌ๐ฉ๐๐๐:
A namespace is a mapping from names to objects. Simply put, it's like a system that assigns a unique name to every object (such as variables, functions, or classes) in Python.๐น ๐๐๐จ๐ฉ๐:
A scope is a textual region of a Python program where a namespace is directly accessible.
Or in Simply, the scope defines the region of code where a name is valid. It determines from which part of the code you can access a particular Python object (like a variable or function).
๐น ๐๐ฒ๐ฉ๐๐ฌ ๐จ๐ ๐๐๐จ๐ฉ๐:
Local Scope: Contains variables & fxn defined within the current function or block of code.
Enclosing Fxn Scopes: Include non-local names from outer functions in nested functions.
Global Scope: Encompasses global names defined at the top level of the current module.
Built-in Scope: Holds Python’s default names (like print() or len()), always available.
๐น ๐๐จ ๐๐๐ฅ๐๐ญ๐ข๐จ๐ง ๐/w ๐๐๐ฆ๐๐ฌ ๐ข๐ง ๐๐ข๐๐๐๐ซ๐๐ง๐ญ ๐๐๐ฆ๐๐ฌ๐ฉ๐๐๐๐ฌ:
Names in different namespaces have no direct connection. For instance, two different modules can both define a function called maximize, and Python won’t get confused. To use such fxns, users must prefix them with the module name to avoid ambiguity.
๐น ๐๐ญ๐ญ๐ซ๐ข๐๐ฎ๐ญ๐๐ฌ ๐จ๐ ๐๐ง ๐๐๐ฃ๐๐๐ญ ๐๐ฌ ๐ ๐๐๐ฆ๐๐ฌ๐ฉ๐๐๐:
An object’s methods and properties also form a namespace. It’s like each object has its own little container for its features.
๐น ๐๐ก๐๐ง ๐๐ซ๐ ๐๐๐ฆ๐๐ฌ๐ฉ๐๐๐๐ฌ ๐๐ซ๐๐๐ญ๐๐?:
Namespaces are created at different moments & have different lifetimes.
The built-in namespace is created when the Python interpreter starts up & never deleted.
The global namespace for a module is created when the module definition is read in. Normally, module namespaces last until the interpreter quits.
The local namespace for a function is created when the function is called, & deleted when the function returns or raises an exception that is not handled within the function.
๐น ๐๐จ๐๐ฎ๐ฅ๐ ๐๐๐ฆ๐๐ฌ๐ฉ๐๐๐:
When you define a function in a module (a Python file), its global scope is that module’s namespace. Imagine the module as a room, & all the names you define inside it are part of that room’s namespace. No matter where you call the function from (even if you use an alias), Python looks inside that module for the function.
๐น ๐๐ฒ๐ง๐๐ฆ๐ข๐ ๐๐๐ฆ๐ ๐๐๐๐ซ๐๐ก:
When you use a name (like calling a function), Python searches for it dynamically at run time. It’s like asking someone in the house to find a specific object for you. But here’s the catch: Python is evolving toward static name resolution (like figuring it out during “compile” time). So, don’t rely too much on dynamic search!
๐น ๐ฆ๐๐ข๐ง ๐๐จ๐๐ฎ๐ฅ๐:
When you run Python code interactively or from a script file, it’s considered part of a module called __main__ which has its global namespace.