Slide 1

Slide 1 text

Python Introspection 101 Py-CU general meeting June 21, 2013

Slide 2

Slide 2 text

Introspection Examining an object to determine what it is, what it knows, and what it is capable of doing. ● type, attributes, functions

Slide 3

Slide 3 text

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) >>> >>> >>> 9.5.is_integer() False

Slide 4

Slide 4 text

Introspection with built-ins

Slide 5

Slide 5 text

type(), is_instance() >>> type("hello") >>> >>> type(9.5) >>> >>> >>> isinstance(9.5,float) True >>> >>> isinstance(9.5,int) False

Slide 6

Slide 6 text

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

Slide 7

Slide 7 text

>>> 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)

Slide 8

Slide 8 text

__dict__ >>> smooth_criminal.__dict__ {'artist': 'Michael Jackson', 'lyrics': ['As He Came Into The Window', 'It Was The Sound Of A Crescendo'], 'title': 'Smooth Criminal'}

Slide 9

Slide 9 text

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']

Slide 10

Slide 10 text

Python interpreters/shells

Slide 11

Slide 11 text

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. ● ....

Slide 12

Slide 12 text

i.e. dir(math)

Slide 13

Slide 13 text

i.e. help(math.ceil)

Slide 14

Slide 14 text

i.e. help(math.pow)

Slide 15

Slide 15 text

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

Slide 16

Slide 16 text

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

Slide 17

Slide 17 text

>>> len.__dict__ Traceback (most recent call last): File "", line 1, in AttributeError: 'builtin_function_or_method' object has no attribute '__dict__' >>> type(int) >> 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 >>> dir(object) ['__class__', '__delattr__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']