7.3. Metaprogramming Namespace

7.3.1. Globals

>>> globals()  
{'__name__': '__main__', '__builtins__': {...}}
>>> print(__name__)
__main__

7.3.2. Variables

The way you always interacted with variables in Python is by using their names directly. But you can also access them through the globals() dictionary:

>>> globals()  
{'__name__': '__main__', '__builtins__': {...}}
>>>
>>> 'x' in globals()
False
>>>
>>> x = 1
>>>
>>> 'x' in globals()
True
>>>
>>> globals()  
{'__name__': '__main__', '__builtins__': {...}, 'x': 1}

You can also modify the value of a variable using the globals() dictionary:

>>> x
1
>>>
>>> globals()['x']
1

7.3.3. Functions

>>> globals()  
{'__name__': '__main__', '__builtins__': {...}}
>>>
>>> 'add' in globals()
False
>>>
>>> def add(a, b):
...     return a + b
>>>
>>> 'add' in globals()
True
>>> globals()  
{'__name__': '__main__', '__builtins__': {...}, 'add': <function add at 0x...>}
>>> add  
<function add at 0x...>
>>>
>>> add(1, 2)
3
>>> add.__call__(1, 2)
3
>>> globals()['add']  
<function add at 0x...>
>>>
>>> globals()['add'](1,2)
3
>>>
>>> globals()['add'].__call__(1, 2)
3

7.3.4. Classes

>>> globals()  
{'__name__': '__main__', '__builtins__': {...}}
>>>
>>> 'User' in globals()
False
>>>
>>> class User:
...     pass
>>>
>>> 'User' in globals()
True
>>>
>>> globals()  
{'__name__': '__main__', '__builtins__': {...}, 'User': <class '__main__.User'>}
>>> User
<class '__main__.User'>
>>>
>>> User()  
<__main__.User object at 0x...>
>>> globals()['User']
<class '__main__.User'>
>>>
>>> globals()['User']()  
<__main__.User object at 0x...>

7.3.5. Class Namespace

>>> class User:
...     AGE_MIN = 18
...     AGE_MAX = 65
...
...     def __init__(self, firstname, lastname, age):
...         self.firstname = firstname
...         self.lastname = lastname
...         self.age = age
...
...     def login(self):
...         return 'Logged in'
...
...     def logout(self):
...         return 'Logged out'
>>> result = vars(User)
>>>
>>> type(result)
<class 'mappingproxy'>
>>>
>>> result  
mappingproxy({'__module__': '__main__',
              '__firstlineno__': 1,
              'AGE_MIN': 18,
              'AGE_MAX': 65,
              '__init__': <function User.__init__ at 0x...>,
              'login': <function User.login at 0x...>,
              'logout': <function User.logout at 0x...>,
              '__static_attributes__': ('age', 'firstname', 'lastname'),
              '__dict__': <attribute '__dict__' of 'User' objects>,
              '__weakref__': <attribute '__weakref__' of 'User' objects>,
              '__doc__': None})