Introspection with Python

16
Introspection with Python “Know thy object…Know thyself” -Socrates

Transcript of Introspection with Python

Introspection with Python“Know thy object…Know thyself”

-Socrates

Introspection

Introspection (tech)

Python

• Strong introspection support

• Consistent object interface

• Flexible typing allows for serious meta-programming

Lets Talk to Some Objects!

What can you tell me?

>>> dir(isinstance)

['__call__', '__class__', '__cmp__', '__delattr__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__']

>>>

Tell me about yourself?

>>> isinstance.__doc__

"isinstance(object, class-or-type-or-tuple) -> bool\n\nReturnwhether an object is an instance of a class or of a subclass thereof.\nWith a type as second argument, return whether that is the object's type.\nThe form using a tuple, isinstance(x, (A, B, ...)), is a shortcut for\nisinstance(x, A) or isinstance(x, B) or ... (etc.)."

>>>

What class do you belong to?

>>> isinstance.__class__

<type 'builtin_function_or_method'>

>>>

Let’s Make a Person>>> class Person(object):

... """represents a human"""

... def talk(self):

... print "Hello, I'm a person!"

...

>>> p = Person()

>>> p.talk()

Hello, I'm a person!

>>> dir(p)

['__class__', '__delattr__', '__dict__', '__doc__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', 'talk']

>>> p.__doc__

'represents a human'

>>>

>>> p.__module__

'__main__'

>>>

Do you have Something I’m Looking For?>>> hasattr(p, 'talk')

True

>>> hasattr(p, 'grunt')

False

>>>

The Inspect Module

>>> inspect.getmodule(p)

<module '__main__' (built-in)>

>>>

>>> inspect.ismethod(p.talk)

True

>>>

Framework Development Using Introspection

Program Structure

• Import all modules in CWD that start with “test”

• Import all class in modules that start with “Test”

• Create instances of classes

• Call all member functions that start with “test”

See Text Editor

Upcoming Events!

Orlando Data Science

January 26

Apache NiFi: Joe Witt of Hortonworks

Meetup.com/orlandodata

Orlando Golang Meetup

February 11

Testing in Go

Meetup.com/orlandogolang

Thank You!

Scott Crespo

SSE, The Topps Company

[email protected]

• Linkedin.com/in/scottcrespo

• Github.com/scottcrespo

• ODev Slack: scottcrespo

• Code Examples: github.com/scottcrespo/introspection_demo