After going through this question
globals()
give the dictionary view of the global namespace(__main__
module).
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, '__package__': None}
>>>
Any new symbol(name), say operator
added to this namespace, will become a member of that global name space.
>>> import operator
>>> globals()
{'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'operator': <module 'operator' (built-in)>, '__package__': None}
>>> globals()['operator']
<module 'operator' (built-in)>
>>>
where operator
is a new str
type key, value is the module
type object.
further on using operator
module(say __abs__
), in current namespace,
>>> globals()['operator']['__abs__']
Traceback (most recent call last):
File "<pyshell#11>", line 1, in <module>
globals()['operator']['__abs__']
TypeError: 'module' object has no attribute '__getitem__'
>>>
It says, operator
module is not a dictionary because there is no attribute by name __getitem__
.
But, all the code from my application(in runtime), will be part of the dictionary shown by globals()
function.
Question:
Ignoring coding standards, In JavaScript, I can use dictionary notation to write my complete code, for example,
> window['Array']
function Array() { [native code] }
> window['Array']['length']
1
In python, Why global namespace members(keys) are only viewed as dictionary members but not their values(like operator
object)? Despite all the subsequent code of your program, is part of that dictionary.