Python3 Globals() And Locals() Contents
Solution 1:
Simple explanation
globals()
refers to the current modules' attribute dictionary.
locals()
refers to the current local variables in your function/code-snippet.
Setting a variable will only ever change locals()
. (Unless you tell python otherwise using the global
or nonlocal
keyword.)
Here an example
By default on module-scope globals is the same dict as locals:
>>> globals() islocals()
True
Since globals is locals in this case, modifying the locals will also modify the globals.
If you create a function and look at locals in there, you will see that locals will differ
>>> deftest():
... print("globals is locals:", globals() islocals())
... print("globals:", globals())
... print("locals:", locals())
>>> test()
globalsislocals: Falseglobals: {'__name__': '__main__', ...}
locals: {}
Locals will automatically update when you change a function-local variable
>>>deftest2():...print("locals 1:", locals())... x = 1...print("locals 2:", locals())>>>test2()
locals 1: {}
locals 2: {'x': 1}
Something similar happens when creating new classes
>>> classTest:
... print("locals:", locals())
locals: {'__module__': '__main__', '__qualname__': 'Test'}
More in-depth explanation
If you want to know why globals and locals are the way they are let's look at what happens under the hood of Python.
Some ground work
All python code passes what equates to the eval
or exec
function at some point. These functions accept three parameters: source
, globals
(defaults to current globals) and locals
(defaults to current locals).
The function globals()
and locals()
will return whatever has been passed into the eval
or exec
functions shown above.
What does the Python Shell do?
If you do
>>>print(globals())
The REPL will internally do something along the lines of
# This variable stores your globals.
_my_main_module = {}
defexec_some_line(line):
returneval(line, globals=_my_main_module, locals=_my_main_module)
# ...
exec_some_line("print(globals())")
As you can see, the Python Shell will at some point set globals
and locals
to the same dict.
Function execution
Internally, function execution will essentially do three things:
- Parse the arguments passed to the function and add them to the local variables.
- Execute the code of the function
- Return its result.
Here a pseudo-algorithm:
def__call__(*args, **kwargs):
local_variables = parse_signature_with_args(args, kwargs)
exec(function_source, function_globals, local_variables)
return function_result
Creating new classes
When using the class-statement, all indented code will be executed separately.
- a new dictionary is created that will act as
locals()
- Your code is executed with said locals.
- The class is created passing locals in
If you execute this code:
classTest:
a = 5
This is approximately what happens:
# 1. A new dictionary is created
_dict = type.__prepare__()
_dict["__module__"] = __name__
_dict["__qualname__"] = "Test"# 2. Execute the codeexec("a = 5", globals=globals(), locals=_dict)
# 3. A class is created
Test = type("Test", (), _dict)
How this maps to module imports
If you import a module an intricate import mechanism starts. This is a simplified overview:
- The interpreter will look if the module has already been imported.
- The interpreter will find the file.
- Then the file is read and parsed
- A module object is created.
- The python script is executed and its globals and locals will be set to the new modules'
__dict__
attribute. - The module object is returned.
It works something like this:
import sys
from types import ModuleType
def__import__(name):
# 1. See if module is already importedif name in sys.modules:
return sys.modules[name]
# 2. Find file.
filename = find_out_path_to_file(name)
# 3. Read and parse filewithopen(filename) as f:
script = f.read()
# 4. Create the new module
module = ModuleType(name)
# 5. Execute the code of the module.exec(script, globals=module.__dict__, locals=module.__dict__)
# 6. Return the new module.return module
Post a Comment for "Python3 Globals() And Locals() Contents"