Home
Python
globals, locals, vars and dir
This page was last reviewed on Jun 11, 2021.
Dot Net Perls
Globals, locals. Python programs can examine their global and local variables. They can even evaluate or compile programs. These features are powerful.
Some examples. We use globals, locals, vars and dir. We further use eval, exec and compile to handle entire programs. Any Python 3 program can use these methods.
Globals. The globals() method returns all the global variables, and their values, in a dictionary. To display them in a program, we can first copy them into another dictionary with dict.
Detail Some hidden variables, like __file__ are shown. These can help us understand the program's environment.
Detail The two user-defined global variables, named value1 and value2, are present as well. They have no surrounding underscores.
value1 = "cat" value2 = "dog" # Copy the globals dict so it does not change size. g = dict(globals()) # Loop over pairs. for item in g.items(): print(item[0], "=", item[1])
__builtins__ = <module 'builtins' (built-in)> __file__ = /Users/sam/Documents/test.py value2 = dog value1 = cat __cached__ = None __name__ = __main__ __doc__ = None
Locals. Locals does the same thing as globals, but for methods. Here we call locals() within a method. It displays the identifier names and values for the 3 local variables.
def method(): value1 = "bird" value2 = "fish" value3 = 400 # Display locals dictionary. print(locals()) # Call the method. method()
{'value3': 400, 'value2': 'fish', 'value1': 'bird'}
Vars. Objects like classes have internal dictionary instances (named __dict__). We can get this dictionary from a class instance with the vars() method.
Detail The class is the argument. Here we display the two fields (attributes) of the Bird class.
class Bird: def __init__(self, wings, color): self.wings = wings self.color = color # Create a bird. b = Bird(2, "blue") # Display internal __dict__ for Bird instance. print(vars(b))
{'color': 'blue', 'wings': 2}
Eval. With eval we evaluate an expression. The expression, specified as a string, is the first argument. The globals, a dictionary, is second.
And The local variables, also a dictionary, is the third argument. This specifies the locals for the program.
Result The eval method returns the result from evaluating the expression. Here, we find that 3 squared is equal to 9.
# Expression is first argument. # ... Global dict is second argument. # ... Local dict is third argument. result = eval("i ** 2", None, {"i": 3}) # Three squared is 9. print(result)
9
Compile. The compile() method returns a code object of the compiled program. We can specify a file name of a Python program to compile.
Detail We can use a string. When we compile a string, we can use an identifying string as the second argument.
Detail We pass the string "exec" to the compile method to indicate the program has more than one line and will later be run with exec.
Warning This method is hard to use. Please consult the Python documentation, as with help(compile) in interactive mode.
# Compile this two-line program. # ... <string> means it is a string, not a file. # ... "exec" means multiple statements are present. code = compile("""x += 1 print(x)""", "<string>", "exec") # Execute compiled code with globals and locals. x = 100 exec(code, globals(), locals())
101
Dir. According to the Python documentation, dir is meant to make interactive mode easier to use. So in interactive mode, you can type "dir()" to see a list of all the globals and locals.
Note This does not get a file list in the current directly (as I first thought it might). None of us are perfect.
bird = 1 horse = 2 # Print list of names in this scope. items = list(dir()) for item in items: print(item)
__builtins__ __cached__ __doc__ __file__ __name__ bird horse
A summary. For casual Python programs, none of these methods are helpful. Some of them, like compile(), are complex, and the detail here is not sufficient for nontrivial usage.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Jun 11, 2021 (image).
Home
Changes
© 2007-2024 Sam Allen.