In many resources I found scope and namespaces are used interchangeably, which seems a bit confusing since they mean different things. Scope defines the region of the code where a name is available.The LEGB rule defines the way names are looked up.Namespace is a place where you look up names.Then I read:names are bind to a namespace according to where they are assigned... (which I believe is the deal with scopes in lexical scoping).functions add an extra namespace layer to your programs [ref.] (don't they add a extra local scope?)all the names assigned inside a function definition are put in the local scope (thenamespace associated with the function call).global scopethat is, a namespace in which variables created (assigned) at the top level of the module file live.*all of the quotes are from learning python 5th edition ch17Are namespaces in Python the way scopes are implemented? Are they the same thing? Can anyone enlighten me?
What is the relationship between scope and namespaces in Python?
python
A namespace is a hash of name, value pairs, a lot like a Python dictionary, but where all the keys are valid name strings. When you do an assignment, like a = 1, you're mutating a namespace. When you make a reference, like print a, Python looks through a list of namespaces to try and find one with the name as a key.A scope defines which namespaces will be looked in and in what order. The scope of any reference always starts in the local namespace, and moves outwards until it reaches the module's global namespace. If you have a function within a class within a module, and there's a reference to a name inside the function, Python looks in the function's namespace, then if the name's not there, Python looks in the class's namespace, then the module's namespace, eventually throwing a NameError if the name isn't found. When we say x is in the function's namespace, we mean it is defined there, locally within the function. When we say x is in the function's scope, we mean x is in the function's namespace or the namespace of the class that the function is defined in or the global namespace that the class is defined in.Whenever you define a class or function, you create a new namespace and a new scope. The namespace is the new, local hash of names. The scope is the implied chain of namespaces that starts at the new namespace, then works its way through any outer namespaces (outer scopes), up to the global namespace (the global scope).The terms can be used almost interchangeably, but that's not because they mean the same thing; it's because they overlap a lot in what they imply.