Reputation: 507
I am just curious, I just recently learned that the Python built-in, global, and local namespace that the interpreter uses to reference objects is basically a Python dictionary.
I am curious as to why when the global()
function is called, the dictionary prints the variable objects in a string but the objects in functions defined refer to a hardware memory address?
For example-
This script:
print("Inital global namespace:")
print(globals())
my_var = "This is a variable."
print("Updated global namespace:")
print(globals())
def my_func():
my_var = "Is this scope nested?"
print("Updated global namespace:")
print(globals())
Outputs this:
Inital global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None}
Updated global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None, 'my_var': 'This is a variable.'}
Updated global namespace:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x10a483208>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'global_check', '__cached__': None, 'my_var': 'This is a variable.', 'my_func': <function my_func at 0x10a40ce18>}
'my_var': 'This is a variable.', 'my_func': <function my_func at 0x10a40ce18>
I understand some people might think these kind of things aren't important, but if I wanted to see the object for a function would I even be able to do such a thing? Does this question make sense?
Upvotes: 2
Views: 2987
Reputation: 3185
When you type my_var
in your code, Python needs to know what that represents. First it checks in locals
and if it doesn't find a reference it checks in globals
. Now Python can evaluate your code when you write 'string' == my_var
. Similarly, when you write the name of a function in your code, Python needs to know what that represents. Since the output of a function can change based on the input, Python can't store a simple value like a string to represent a function in globals
. Instead it stores the memory reference so that when you type my_func()
, it can go to that memory store and use the function to compute the output.
Upvotes: 2
Reputation: 36
use global my_var
Then you can assign your global variables in local namespaces
Upvotes: 0