Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Py-CU Lightning Talk - Python Introspection 101

Py-CU Lightning Talk - Python Introspection 101

gnarlinsky

June 21, 2013
Tweet

Other Decks in Programming

Transcript

  1. Introspection Examining an object to determine what it is, what

    it knows, and what it is capable of doing. • type, attributes, functions
  2. Everything is an object in Python • Object = collection

    of data and associated functions; subclassable. • Python objects: modules, functions, strings, lists, ints, ........ • Everything -- all the data -- is represented by objects and relationships between objects. >>> type(9.5) <type 'float'> >>> >>> >>> 9.5.is_integer() False
  3. type(), is_instance() >>> type("hello") <type 'str'> >>> >>> type(9.5) <type

    'float'> >>> >>> >>> isinstance(9.5,float) True >>> >>> isinstance(9.5,int) False
  4. class Song(object): def __init__(self, title, artist, lyrics=[]): self.title = title

    self.artist = artist self.lyrics = lyrics def sing_song(self): for line in self.lyrics: print line
  5. >>> smooth_criminal = Song("Smooth Criminal", "Michael Jackson") >>> smooth_criminal.lyrics =

    ["As He Came Into The Window", "It Was The Sound Of A Crescendo"] >>> >>> smooth_criminal.title 'Smooth Criminal' >>> smooth_criminal.artist 'Michael Jackson' >>> smooth_criminal.sing_song() As He Came Into The Window It Was The Sound Of A Crescendo >>> type(smooth_criminal) <class '__main__.Song'>
  6. __dict__ >>> smooth_criminal.__dict__ {'artist': 'Michael Jackson', 'lyrics': ['As He Came

    Into The Window', 'It Was The Sound Of A Crescendo'], 'title': 'Smooth Criminal'}
  7. dir() >>> dir(smooth_criminal) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__',

    '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'artist', 'lyrics', 'sing_song', 'title']
  8. bpython: an interface to the Python interpreter • In-line syntax

    highlighting. • Readline-like autocomplete with suggestions displayed as you type. • Expected parameter list for any Python function. • ....
  9. What else... • define functions without names • call functions

    with arguments out of order • reference functions whose names you don't know until runtime • get info for traceback
  10. Python Introspection 102 preview: find which class defines a method

    >>> from my_introspect import introspect_this >>> introspect_this(b) __init__ is defined in class "B" (lib_b.py) bye_you is defined in class "B" (lib_b.py) hello_you is defined in class "B" (lib_b.py) say_bye is defined in class "A" (lib_a.py) say_hello is defined in class "A" (lib_a.py) $ python >>> from lib_b import B >>> b = B("John Doe") >>> dir(b) ['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'bye_someone', 'greet_someone', 'name', 'say_bye', 'say_hello' versus
  11. >>> len.__dict__ Traceback (most recent call last): File "<stdin>", line

    1, in <module> AttributeError: 'builtin_function_or_method' object has no attribute '__dict__' >>> type(int) <type 'type' >>> dir(__builtins__) ['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', '_', '__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', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'format', 'frozenset', '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', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> object <type 'object'> >>> dir(object) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']