is 'globals()' a namespace? and does a namespace work like a dictionary in the sense that you can add a key to a dictionary just by:
Yes globals() are a namespace.
A namespace is it`s just like dictionary.
*** Python 2.7.2 (default, Jun 12 2011, 15:08:59) [MSC v.1500 32 bit (Intel)] on win32. ***
>>> a = 5
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'__package__': None,
'a': 5,
'pyscripter': <module 'pyscripter' (built-in)>}
>>> globals()['a']
5
>>> globals()['b'] = 6 #same as b = 6
>>> b
6
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'__package__': None,
'a': 5,
'b': 6,
'pyscripter': <module 'pyscripter' (built-in)>}
>>>
Python has 3 namespaces global namespace, local namespace, built-in namespace
.
We can take a look at local namespace.
>>> def foo():
... x = 'i am local'
... return x
...
>>> foo()
'i am local'
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'__package__': None,
'foo': <function foo at 0x01EE5AF0>,
'pyscripter': <module 'pyscripter' (built-in)>}
>>> x #if we try to access x
Traceback (most recent call last):
File "<interactive input>", line 1, in <module>
NameError: name 'x' is not defined
>>> #x are local to fuction foo
>>> locals()
{'__builtins__': <module '__builtin__' (built-in)>,
'__doc__': None,
'__name__': '__main__',
'__package__': None,
'foo': <function foo at 0x01EE5AF0>,
'pyscripter': <module 'pyscripter' (built-in)>}
>>> def foo():
... global x #make x global
... x = 'i am no longer only local'
... return x
... …