Skip to content

Instantly share code, notes, and snippets.

@amitsaha
Created August 27, 2012 09:04
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save amitsaha/3486802 to your computer and use it in GitHub Desktop.
Save amitsaha/3486802 to your computer and use it in GitHub Desktop.
Demo code using the Python inspect module
''' Demo script experimenting with various features of the
inspect module
'''
# To be run with Python3.3
from inspect_test import MyClass
from inspect_test import myfunc
from inspect_test import mygen
import inspect
from inspect import signature
if __name__=='__main__':
# demo of inspect.getsource()
obj = MyClass()
# Get the source file where this class
if inspect.isclass(MyClass):
print(inspect.getsource(MyClass))
# demo of inspect.getmembers()
# Get the members
print('Object Members:: \n')
for member in inspect.getmembers(obj):
print(member)
print('\n\nRandom Expirements \n')
# experiments with builtins
functions = [obj.fun1, open, dir, myfunc]
for func in functions:
if inspect.isbuiltin(func):
print('{0:s} is built in'.format(func.__name__))
else:
print('{0:s} is not built in'.format(func.__name__))
print('\n')
# experiments with signatures
# Introduced in Python 3.3
functions = [obj.fun1, inspect.isclass]
for func in functions:
sig = signature(func)
print('Parameters: {0:s}:: {1:s}'.format(func.__name__,str(sig)))
print('\n')
# experiments with frames
myfunc()
# generator experiments
generator = mygen()
# get the current state
print(inspect.getgeneratorstate(generator))
count = 0
for fib in generator:
# get the current state
print(inspect.getgeneratorstate(generator))
#print the number yielded
print(fib)
if count >= 10:
break
count = count + 1
print(inspect.getgeneratorstate(generator))
import inspect
class MyClass:
""" A class """
def __init__(self):
pass
def fun1(self, a, b):
return 0
def fun2(self):
return 1
def myfunc():
# frame demo
currentframe = inspect.currentframe()
callgraph=inspect.getouterframes(currentframe)
print('Call Graph for {0:s}'.format(myfunc.__name__))
for record in callgraph:
frameinfo = inspect.getframeinfo(record[0])
print(frameinfo.function)
# Simple generator returning fibonacci numbers
def mygen():
a = 0
b = 1
while True:
c = a+b
yield c
a,b = b,c
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment