__builtins__
- names in builtins are always loaded in global scope with this name__main__
- turns main script into a module that holds the main programs execution
import sys
sys.__dict__.keys()
python will return the first variable or function name that matches your search
counter = 0 # A global name
>>> def update_counter():
... global counter # Declare counter as global
... counter = counter + 1 # Successfully update the counter
...
>>> update_counter()
>>> counter
1
>>> update_counter()
>>> counter
2
>>> update_counter()
>>> counter
3
nonlocal my_var # Try to use nonlocal in the global scope
File "<stdin>", line 1
SyntaxError: nonlocal declaration not allowed at module level
>>> def func():
... nonlocal var # Try to use nonlocal in a local scope
... print(var)
...
File "<stdin>", line 2
SyntaxError: no binding for nonlocal 'var' found
globals()
- returns reference to current global scope or namespace dictlocals()
- updates and returns dict that holds copy of current state of local scope or namespacevars()
- builtin function that returns .dict attribute of module, class, instance or any other object with dict attributedir()
- can use without arguments to get list of names in current scope, with argument function will try to return a list of valid attributes for object