{ "metadata": { "name": "" }, "nbformat": 3, "nbformat_minor": 0, "worksheets": [ { "cells": [ { "cell_type": "markdown", "metadata": {}, "source": [ "[Python for Developers](http://ricardoduarte.github.io/python-for-develoepers/#content)\n", "===================================\n", "First Edition\n", "-----------------------------------\n", "\n", "Chapter 14: Introspection\n", "=============================\n", "_____________________________\n", "Introspection or reflection is the ability of software to identify and report its own internal structures, such as types, variable scope, methods and attributes.\n", "\n", "Native interpreter functions for introspection:\n", "\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "
FunctionReturns
type(object)The typo (class) of the object
id(object)object identifier
locals()local variables dictionary
globals()global variables dictionary
vars(object)object symbols dictionary
len(object)size of an object
dir(object)A list of object structures
help(object)Object doc strings
repr(object)Object representation
isinstance(object, class)True if object is derived from class
issubclass(subclass, class)True if object inherits the class
\n", "\n", "The object identifier is a unique number that is used by the interpreter for identifying the objects internally.\n", "\n", " Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "# Getting some information\n", "# about global objects in the program\n", "\n", "from types import ModuleType\n", "\n", "def info(n_obj):\n", "\n", " # Create a reference to the object\n", " obj = globals()[n_obj]\n", "\n", " # Show object information \n", " print 'Name of object:', n_obj\n", " print 'Identifier:', id(obj)\n", " print 'Typo:', type(obj)\n", " print 'Representation:', repr(obj)\n", "\n", " # If it is a module\n", " if isinstance(obj, ModuleType):\n", " print 'itens:'\n", " for item in dir(obj):\n", " print item\n", " print\n", "\n", "# Showing information\n", "for n_obj in dir()[:10]: # The slice [:10] is used just to limit objects\n", " info(n_obj)" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Name of object: In\n", "Identifier: 58164072\n", "Typo: \n", "Representation: ['', u\"# Getting some information\\n# about global objects in the program\\n\\nfrom types import ModuleType\\n\\ndef info(n_obj):\\n\\n # Create a refer\\xeance to the object\\n obj = globals()[n_obj]\\n\\n # Show object information \\n print 'Name of object:', n_obj\\n print 'Identifier:', id(obj)\\n print 'Typo:', type(obj)\\n print 'Representation:', repr(obj)\\n\\n # If it is a module\\n if isinstance(obj, ModuleType):\\n print 'itens:'\\n for item in dir(obj):\\n print item\\n print\\n\\n# Showing information\\nfor n_obj in dir()[:10]: # The slice [:10] is used just to limit objects\\n info(n_obj)\"]\n", "\n", "Name of object: ModuleType\n", "Identifier: 8686656\n", "Typo: \n", "Representation: \n", "\n", "Name of object: Out\n", "Identifier: 58493664\n", "Typo: \n", "Representation: {}\n", "\n", "Name of object: _\n", "Identifier: 140086544672008\n", "Typo: \n", "Representation: ''\n", "\n", "Name of object: __\n", "Identifier: 140086544672008\n", "Typo: \n", "Representation: ''\n", "\n", "Name of object: ___\n", "Identifier: 140086544672008\n", "Typo: \n", "Representation: ''\n", "\n", "Name of object: __builtin__\n", "Identifier: 140086544653064\n", "Typo: \n", "Representation: \n", "itens:\n", "ArithmeticError\n", "AssertionError\n", "AttributeError\n", "BaseException\n", "BufferError\n", "BytesWarning\n", "DeprecationWarning\n", "EOFError\n", "Ellipsis\n", "EnvironmentError\n", "Exception\n", "False\n", "FloatingPointError\n", "FutureWarning\n", "GeneratorExit\n", "IOError\n", "ImportError\n", "ImportWarning\n", "IndentationError\n", "IndexError\n", "KeyError\n", "KeyboardInterrupt\n", "LookupError\n", "MemoryError\n", "NameError\n", "None\n", "NotImplemented\n", "NotImplementedError\n", "OSError\n", "OverflowError\n", "PendingDeprecationWarning\n", "ReferenceError\n", "RuntimeError\n", "RuntimeWarning\n", "StandardError\n", "StopIteration\n", "SyntaxError\n", "SyntaxWarning\n", "SystemError\n", "SystemExit\n", "TabError\n", "True\n", "TypeError\n", "UnboundLocalError\n", "UnicodeDecodeError\n", "UnicodeEncodeError\n", "UnicodeError\n", "UnicodeTranslateError\n", "UnicodeWarning\n", "UserWarning\n", "ValueError\n", "Warning\n", "ZeroDivisionError\n", "__IPYTHON__\n", "__IPYTHON__active\n", "__debug__\n", "__doc__\n", "__import__\n", "__name__\n", "__package__\n", "abs\n", "all\n", "any\n", "apply\n", "basestring\n", "bin\n", "bool\n", "buffer\n", "bytearray\n", "bytes\n", "callable\n", "chr\n", "classmethod\n", "cmp\n", "coerce\n", "compile\n", "complex\n", "copyright\n", "credits\n", "delattr\n", "dict\n", "dir\n", "divmod\n", "dreload\n", "enumerate\n", "eval\n", "execfile\n", "file\n", "filter\n", "float\n", "format\n", "frozenset\n", "get_ipython\n", "getattr\n", "globals\n", "hasattr\n", "hash\n", "help\n", "hex\n", "id\n", "input\n", "int\n", "intern\n", "isinstance\n", "issubclass\n", "iter\n", "len\n", "license\n", "list\n", "locals\n", "long\n", "map\n", "max\n", "memoryview\n", "min\n", "next\n", "object\n", "oct\n", "open\n", "ord\n", "pow\n", "print\n", "property\n", "range\n", "raw_input\n", "reduce\n", "reload\n", "repr\n", "reversed\n", "round\n", "set\n", "setattr\n", "slice\n", "sorted\n", "staticmethod\n", "str\n", "sum\n", "super\n", "tuple\n", "type\n", "unichr\n", "unicode\n", "vars\n", "xrange\n", "zip\n", "\n", "Name of object: __builtins__\n", "Identifier: 140086544653064\n", "Typo: \n", "Representation: \n", "itens:\n", "ArithmeticError\n", "AssertionError\n", "AttributeError\n", "BaseException\n", "BufferError\n", "BytesWarning\n", "DeprecationWarning\n", "EOFError\n", "Ellipsis\n", "EnvironmentError\n", "Exception\n", "False\n", "FloatingPointError\n", "FutureWarning\n", "GeneratorExit\n", "IOError\n", "ImportError\n", "ImportWarning\n", "IndentationError\n", "IndexError\n", "KeyError\n", "KeyboardInterrupt\n", "LookupError\n", "MemoryError\n", "NameError\n", "None\n", "NotImplemented\n", "NotImplementedError\n", "OSError\n", "OverflowError\n", "PendingDeprecationWarning\n", "ReferenceError\n", "RuntimeError\n", "RuntimeWarning\n", "StandardError\n", "StopIteration\n", "SyntaxError\n", "SyntaxWarning\n", "SystemError\n", "SystemExit\n", "TabError\n", "True\n", "TypeError\n", "UnboundLocalError\n", "UnicodeDecodeError\n", "UnicodeEncodeError\n", "UnicodeError\n", "UnicodeTranslateError\n", "UnicodeWarning\n", "UserWarning\n", "ValueError\n", "Warning\n", "ZeroDivisionError\n", "__IPYTHON__\n", "__IPYTHON__active\n", "__debug__\n", "__doc__\n", "__import__\n", "__name__\n", "__package__\n", "abs\n", "all\n", "any\n", "apply\n", "basestring\n", "bin\n", "bool\n", "buffer\n", "bytearray\n", "bytes\n", "callable\n", "chr\n", "classmethod\n", "cmp\n", "coerce\n", "compile\n", "complex\n", "copyright\n", "credits\n", "delattr\n", "dict\n", "dir\n", "divmod\n", "dreload\n", "enumerate\n", "eval\n", "execfile\n", "file\n", "filter\n", "float\n", "format\n", "frozenset\n", "get_ipython\n", "getattr\n", "globals\n", "hasattr\n", "hash\n", "help\n", "hex\n", "id\n", "input\n", "int\n", "intern\n", "isinstance\n", "issubclass\n", "iter\n", "len\n", "license\n", "list\n", "locals\n", "long\n", "map\n", "max\n", "memoryview\n", "min\n", "next\n", "object\n", "oct\n", "open\n", "ord\n", "pow\n", "print\n", "property\n", "range\n", "raw_input\n", "reduce\n", "reload\n", "repr\n", "reversed\n", "round\n", "set\n", "setattr\n", "slice\n", "sorted\n", "staticmethod\n", "str\n", "sum\n", "super\n", "tuple\n", "type\n", "unichr\n", "unicode\n", "vars\n", "xrange\n", "zip\n", "\n", "Name of object: __doc__\n", "Identifier: 48549272\n", "Typo: \n", "Representation: 'Automatically created module for IPython interactive environment'\n", "\n", "Name of object: __name__\n", "Identifier: 140086544389776\n", "Typo: \n", "Representation: '__main__'\n", "\n" ] } ], "prompt_number": 1 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Python also has a module called *types*, which has the definitions of the basic types of the interpreter.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import types\n", "\n", "s = ''\n", "if isinstance(s, types.StringType):\n", " print 's is a string.'" ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "s is a string.\n" ] } ], "prompt_number": 2 }, { "cell_type": "markdown", "metadata": {}, "source": [ "Through introspection, it is possible to determine the fields of a database table, for example.\n", "\n", "Inspect\n", "-------\n", "The module *inspect* provides a set of high-level functions that allow for introspection to investigate types, collection items, classes, functions, source code and the runtime stack of the interpreter.\n", "\n", "Example:" ] }, { "cell_type": "code", "collapsed": false, "input": [ "import os.path\n", "# inspect: \"friendly\" introspection module\n", "import inspect\n", "\n", "print 'Object:', inspect.getmodule(os.path)\n", "\n", "print 'Class?', inspect.isclass(str)\n", "\n", "# Lists all functions that exist in \"os.path\"\n", "\n", "print 'Member:',\n", "\n", "for name, struct in inspect.getmembers(os.path):\n", "\n", " if inspect.isfunction(struct):\n", " print name, " ], "language": "python", "metadata": {}, "outputs": [ { "output_type": "stream", "stream": "stdout", "text": [ "Object: \n", "Class? True\n", "Member: _joinrealpath abspath basename commonprefix dirname exists expanduser expandvars getatime getctime getmtime getsize isabs isdir isfile islink ismount join lexists normcase normpath realpath relpath samefile sameopenfile samestat split splitdrive splitext walk\n" ] } ], "prompt_number": 3 }, { "cell_type": "markdown", "metadata": {}, "source": [ "The functions that work with the stack of the interpreter should be used with caution because it is possible to create cyclic references (a variable that points to the stack item that has the variable itself). The existence of references to stack items slows the destruction of the items by the garbage collector of the interpreter." ] }, { "cell_type": "code", "collapsed": false, "input": [], "language": "python", "metadata": {}, "outputs": [ { "html": [ "\n", "" ], "output_type": "pyout", "prompt_number": 1, "text": [ "" ] } ], "prompt_number": 1 } ], "metadata": {} } ] }