Python Forum
global / local namespace
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
global / local namespace
#1
hello,
recently i have 'discovered' a little bit 'strange' block of code.

a = 5
print(id(a))

if a == 5:
	a = a + 2
	print(a)
	print(id(a))

print(id(a)) 
the output:
Output:
10924160 7 10924224 10924224
it turns out that the interpreter see the ( already ... 'localized'!? ) object 'a' in the global name space also.
should the 'a' not be encapsulated in the local scope of the 'if-statement' and not accessible from the global name space?

thanks in advance!
Reply
#2
throw in a twist:
>>> a = 5
>>> b = a
>>> print(id(a))
9342464
>>> print(id(b))
9342464
>>> if a == 5:
...     a = a + 2
...     print(a)
...     print(id(a))
... 
7
9342528
>>> print(id(a))
9342528
>>> print(id(b))
9342464
>>>
Reply
#3
(Oct-31-2018, 03:27 PM)nzcan Wrote: should the 'a' not be encapsulated in the local scope of the 'if-statement' and not accessible from the global name space?
There is no local namespace for block statements such as if, while, for. They use the surrounding namespace. Function bodies have a local namespace that is different for each execution of the function. Class definitions bodies also have their own namespace
>>> x = object()
>>> class A:
...     x = object()
...     print(id(x))
... 
139880381153440
>>> print(id(x))
139880381153648
Note that for small integers, things are different because python (at least CPython) keeps a single instance
for each of them. On my version of python, it goes up to 256 included
>>> a = 256
>>> b = 256
>>> a is b # the names a and b share the same integer instance
True
>>> a = 257
>>> b = 257
>>> a is b # two integer instances were created
False
Reply
#4
The code just shows that strings are not mutable, and has nothing to do with local vs global namespaces. This gives the same results
a = 5
print(id(a))
 
##if a == 5:
a = a + 2
print(a)
print(id(a))
 
print(id(a))
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Decorator and namespace. JayIvhen 2 3,598 Oct-26-2018, 03:56 PM
Last Post: nilamo

Forum Jump:

User Panel Messages

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