C-Sharp | Java | Python | Swift | GO | WPF | Ruby | Scala | F# | JavaScript | SQL | PHP | Angular | HTML
Hidden: Some hidden variables, like __file__ are shown. These can help us understand the program's environment.
User-defined: The two user-defined global variables, named value1 and value2, are present as well. They have no surrounding underscores.
Python program that uses globals
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])
Output
__builtins__ = <module 'builtins' (built-in)>
__file__ = /Users/sam/Documents/test.py
value2 = dog
value1 = cat
__cached__ = None
__name__ = __main__
__doc__ = None
Python program that uses locals
def method():
value1 = "bird"
value2 = "fish"
value3 = 400
# Display locals dictionary.
print(locals())
# Call the method.
method()
Output
{'value3': 400, 'value2': 'fish', 'value1': 'bird'}
Argument: The class is the argument. Here we display the two fields (attributes) of the Bird class.
Python program that uses vars
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))
Output
{'color': 'blue', 'wings': 2}
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.
Python program that uses eval
# 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)
Output
9
Or: We can use a string. When we compile a string, we can use an identifying string as the second argument.
Exec: 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.
Caution: This method is hard to use. Please consult the Python documentation, as with help(compile) in interactive mode.
Python program that uses compile, exec
# 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())
Output
101
Note: This does not get a file list in the current directly (as I first thought it might). None of us are perfect.
Python program that uses dir
bird = 1
horse = 2
# Print list of names in this scope.
items = list(dir())
for item in items: print(item)
Output
__builtins__
__cached__
__doc__
__file__
__name__
bird
horse