Basic Introspection

You don't start with a clean slate, but in a well defined universe with keywords (and their associated grammar), builtins and a namespace you can fill with data and functionality ... and more namespaces obviously.


In [3]:
import keyword
print keyword.kwlist


['and', 'as', 'assert', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'exec', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'print', 'raise', 'return', 'try', 'while', 'with', 'yield']

In [4]:
print keyword.iskeyword('and')
print keyword.iskeyword('keyword')


True
False

In [1]:
dir(__builtins__)


Out[1]:
['ArithmeticError',
 'AssertionError',
 'AttributeError',
 'BaseException',
 'BufferError',
 'BytesWarning',
 'DeprecationWarning',
 'EOFError',
 'Ellipsis',
 'EnvironmentError',
 'Exception',
 'False',
 'FloatingPointError',
 'FutureWarning',
 'GeneratorExit',
 'IOError',
 'ImportError',
 'ImportWarning',
 'IndentationError',
 'IndexError',
 'KeyError',
 'KeyboardInterrupt',
 'LookupError',
 'MemoryError',
 'NameError',
 'None',
 'NotImplemented',
 'NotImplementedError',
 'OSError',
 'OverflowError',
 'PendingDeprecationWarning',
 'ReferenceError',
 'RuntimeError',
 'RuntimeWarning',
 'StandardError',
 'StopIteration',
 'SyntaxError',
 'SyntaxWarning',
 'SystemError',
 'SystemExit',
 'TabError',
 'True',
 'TypeError',
 'UnboundLocalError',
 'UnicodeDecodeError',
 'UnicodeEncodeError',
 'UnicodeError',
 'UnicodeTranslateError',
 'UnicodeWarning',
 'UserWarning',
 'ValueError',
 'Warning',
 'ZeroDivisionError',
 '__IPYTHON__',
 '__IPYTHON__active',
 '__debug__',
 '__doc__',
 '__import__',
 '__name__',
 '__package__',
 'abs',
 'all',
 'any',
 'apply',
 'basestring',
 'bin',
 'bool',
 'buffer',
 'bytearray',
 'bytes',
 'callable',
 'chr',
 'classmethod',
 'cmp',
 'coerce',
 'compile',
 'complex',
 'copyright',
 'credits',
 'delattr',
 'dict',
 'dir',
 'divmod',
 'dreload',
 'enumerate',
 'eval',
 'execfile',
 'file',
 'filter',
 'float',
 'format',
 'frozenset',
 'get_ipython',
 'getattr',
 'globals',
 'hasattr',
 'hash',
 'help',
 'hex',
 'id',
 'input',
 'int',
 'intern',
 'isinstance',
 'issubclass',
 'iter',
 'len',
 'license',
 'list',
 'locals',
 'long',
 'map',
 'max',
 'memoryview',
 'min',
 'next',
 'object',
 'oct',
 'open',
 'ord',
 'pow',
 'print',
 'property',
 'range',
 'raw_input',
 'reduce',
 'reload',
 'repr',
 'reversed',
 'round',
 'set',
 'setattr',
 'slice',
 'sorted',
 'staticmethod',
 'str',
 'sum',
 'super',
 'tuple',
 'type',
 'unichr',
 'unicode',
 'vars',
 'xrange',
 'zip']

In [2]:
globals()


Out[2]:
{'In': ['', u'locals()', u'globals()'],
 'Out': {1: {...}},
 '_': {...},
 '_1': {...},
 '__': '',
 '___': '',
 '__builtin__': <module '__builtin__' (built-in)>,
 '__builtins__': <module '__builtin__' (built-in)>,
 '__doc__': 'Automatically created module for IPython interactive environment',
 '__name__': '__main__',
 '_dh': [u'/home/obestwalter/work/presentation_stack/python-course/introspection'],
 '_i': u'locals()',
 '_i1': u'locals()',
 '_i2': u'globals()',
 '_ih': ['', u'locals()', u'globals()'],
 '_ii': u'',
 '_iii': u'',
 '_oh': {1: {...}},
 '_sh': <module 'IPython.core.shadowns' from '/home/obestwalter/work/presentation_stack/python-course/.direnv/python-2.7.6/local/lib/python2.7/site-packages/IPython/core/shadowns.pyc'>,
 'exit': <IPython.core.autocall.ZMQExitAutocall at 0x7f5b505cd510>,
 'get_ipython': <bound method ZMQInteractiveShell.get_ipython of <ipykernel.zmqshell.ZMQInteractiveShell object at 0x7f5b53683a50>>,
 'quit': <IPython.core.autocall.ZMQExitAutocall at 0x7f5b505cd510>}

In [5]:
locals() == globals()


Out[5]:
True

In [6]:
def function_is_new_namespace():
    somevar = 1
    print locals()
    
function_is_new_namespace()


{'somevar': 1}