Python Forum
Namespace and scope difference
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Namespace and scope difference
#1
I have read through a number of article about this but still can't get a sastified answer, can you guys help me!

What is the relationship between "Namespace" and "scope" can we say a scope is a superset of namespaces ? I mean we can access the outer namespace's name from the inner namespace but not vice versa, correct me if i'm wrong!. And the namespace only contain the name in that specific namespace, not the name in the inner?:

>>> a=2
>>> def inner():
...     b=3
...
>>> dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'inner']
Reply
#2
A namespace is a mapping of names to objects. Common namespaces include modules and classes. They're typically implemented as dictionaries. However, note that a dictionary key can be something that is invalid as a Python name.

The scope of a namespace is the part of the program where the namespace can be referred to without qualification (that is, 'foo', as opposed to 'bar.foo'). So scope is not a superset of namespaces, it a relationship between namespaces and programs.

You can typically access outer namespaces from inner namespaces, but there are limits. One function can't access the namespace of the function that called it, as is possible in some other programming languages. However, a function in a module can access the names in the module's namespace. But note that you can have the same name in the function's namespace and the module's namespace. The function won't be able to access the one in the module's namespace (without some tricks), because it find the function's version of the name and stops there.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#3
Maybe this read will help you: what is relationship between namespace and scope
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#4
(Jul-03-2019, 01:09 PM)ichabod801 Wrote: One function can't access the namespace of the function that called it, as is possible in some other programming languages.
I don't understand ! Isn't this a function access outer function's namespace?

>>> def inner():
...     y=1
...     def innermost():
...         print(y)
...     innermost()
...
...
>>> inner()
1
Reply
#5
(Jul-03-2019, 01:32 PM)Uchikago Wrote: Isn't this a function access outer function's namespace?

Yes, but that's not a function calling another function, it's a function defined within another function.

def foo(x):
   z = x + 2
   return bar(x)

def bar(y):
   return y * z

foo()
The above will fail because bar does not have access to z.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#6
In order to fully understand namespace and scope you should familiarise yourself with closure as well. Python supports closures: functions that refer to variables from the scope in which they were defined.

ichabod801 used terms 'typically' and 'without some tricks' for a reason. There is much subtlety and in order to understand you must look at the whole picture.

There are behaviours which seem illogical at first but actually make sense if you think about it. Just to illustrate:

>>> def inner():
...     y = 1
...     def innermost():
...         y = 2
...     innermost()
...     print(y)
... 
>>> inner()
1
>>> def inner():
...     y = [1]
...     def innermost():
...         y[0] = 2
...     innermost()
...     print(y)
... 
>>> inner()
[2]
EDIT:

You should also understand difference between reference and assignment:

When you reference a variable in an expression, the Python interpreter will traverse the scope to resolve the reference in following order:

- current function’s scope
- any enclosing scopes (like containing functions)
- scope of the module that contains the code (global scope)
- built-in scope (that contains functions like int and abs)

If Python doesn't find defined variable with the referenced name, then a NameError exception is raised.

Assigning a value to a variable works differently. If the variable is already defined in the current scope, then it will just take on the new value. If the variable doesn’t exist in the current scope, then Python treats the assignment as a variable definition. The scope of the newly defined variable is the function that contains the assignment.
I'm not 'in'-sane. Indeed, I am so far 'out' of sane that you appear a tiny blip on the distant coast of sanity. Bucky Katt, Get Fuzzy

Da Bishop: There's a dead bishop on the landing. I don't know who keeps bringing them in here. ....but society is to blame.
Reply
#7
To add to what perfringo said, note that Python looks ahead for assignments:

>>> def foo():
...    print(x)
...    x = 3
...    return x + 5
...
>>> x = 5
>>> foo()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 2, in foo
UnboundLocalError: local variable 'x' referenced before assignment
Python saw that you were going to assign to x in the function, so it decided was in local scope. Then it processed the print call, and couldn't find x in the local scope, and didn't bother to check the further scopes as it otherwise would. If you didn't have the assignment, it would work just like prefringo says.

It is indeed a subtle and twisty topic.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#8
I came accross this:
Quote:In Python, these non-local variables are read only by default and we must declare them explicitly as non-local (using nonlocal keyword) in order to modify them.
This isn't quite true right? i mean we can mutate mutable object just like what perfringo did with his example
(Jul-03-2019, 02:06 PM)perfringo Wrote: >>> def inner():
...     y = [1]
...     def innermost():
...         y[0] = 2
...     innermost()
...     print(y)
...
>>> inner()
[2]
Reply
#9
When you are mutating that list, you are no changing y's reference. y still points to the same place, just what is in that place has changed. If you tried to change how y is aimed, by saying y = [2], that would not change the outer y. If you declared y as nonlocal, y = [2] would change the outer y. However nonlocal (and it's cousin global) are generally frowned upon. They manipulate the scope of namespaces, and make your code hard to follow for people expecting namespaces to work in a certain way. Namespaces and scope are tricky enough without changing them around.
Craig "Ichabod" O'Brien - xenomind.com
I wish you happiness.
Recommended Tutorials: BBCode, functions, classes, text adventures
Reply
#10
x=50
def func(x):
    print(f'X is {x}')
    x=200
    print(x)
func(x)
What about this, it worked because we have a parameter which create a local variable, so when we say
Quote:print(f'X is {x}')
X is the local variable not the global variable, they just shared the same object, correct me if i'm wrong please!
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  How to create a variable only for use inside the scope of a while loop? Radical 10 1,666 Nov-07-2023, 09:49 AM
Last Post: buran
  Library scope mike_zah 2 830 Feb-23-2023, 12:20 AM
Last Post: mike_zah
  Scope of variable confusion Mark17 10 2,821 Feb-24-2022, 06:03 PM
Last Post: deanhystad
  Variable scope issue melvin13 2 1,525 Nov-29-2021, 08:26 PM
Last Post: melvin13
  'namespace' shorthand for function arguments? shadowphile 5 2,573 Aug-11-2021, 09:02 PM
Last Post: shadowphile
  Variable scope - "global x" didn't work... ptrivino 5 3,028 Dec-28-2020, 04:52 PM
Last Post: ptrivino
  Python Closures and Scope muzikman 2 1,794 Dec-14-2020, 11:21 PM
Last Post: muzikman
  [PyKML] Loop through all Placemarks; Remove namespace Winfried 2 3,408 Aug-28-2020, 09:24 AM
Last Post: Winfried
  Block of code, scope of variables and surprising exception arbiel 8 3,394 Apr-06-2020, 07:57 PM
Last Post: arbiel
  Beginner question: lxml's findall in an xml namespace aecklers 0 2,894 Jan-22-2020, 10:53 AM
Last Post: aecklers

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020