Sunday, November 2, 2014

Python Module: inspect


Always the first thing:
import inspect

Case 1: 
To know what arguments in one function.
use inspect.getargspec(functionName)
it will return a tuple type object, the first item contains a list of arguments of this function.

Example:
def myFunc(arg1, arg2, arg3):
    pass
inspect.getargspec(myFunc)[0]
#Result: ['arg1', 'arg2', 'arg3']


Case 2:
To find what members(functions, methods, classes) inside a module,
use following codes:

Example:
# get functions in a module
inspect.getmembers(ModuleName, predicate=inspect.isfunction)

# get classes in a module
inspect.getmembers(ModuleName, predicate=inspect.isclass)

# get methods in a class
inspect.getmembers(ClassName, predicate=inspect.ismethod)

# get built-in methods in a class
inspect.getmembers(ClassName, predicate=inspect.isbuiltin)


Case 3:
those will return a list of tuples.
For each tuple, first item is the name of the member, second item is its memory address.

Example:
import os

# get modules in os
inspect.getmembers(os, predicate = inspect.ismodule)

# get functions in os
inspect.getmembers(os, predicate=inspect.isfunction)

# get classes in os
inspect.getmembers(os, predicate=inspect.isclass)

# get built-in methods in os
inspect.getmembers(os, predicate=inspect.isbuiltin)

# get methods in a class in os
# get the a class
class = inspect.getmembers(os, predicate=inspect.isclass)[1][1]
inspect.getmembers(class, predicate=inspect.ismethod)


Case 4:
To find the class inherit tree hierarchy by inspect.getclasstree([ClassName, ClassName, ...])
it will return a list of all parents of each class.

Example:
# get two classes in os
firstClass = inspect.getmembers(os, predicate=inspect.isclass)[0][1]
secondClass = inspect.getmembers(os, predicate=inspect.isclass)[1][1]

inspect.getclasstree([firstClass, secondClass])

No comments:

Post a Comment