PythonReflection

From TkkrLab

Jump to: navigation, search

This is a part of PythonMaterial.

function inspection

""" Show the way arguments will be interpreted """
import inspect
 
 
def fn(first, second="hi", *listed, **named):  # pylint: disable-msg=W0613
    """ This function will not be called """
    print "unreached"
 
print inspect.getargspec(fn)
print inspect.getcallargs(fn, "this", "is", "not", "nothing", rest=1)

class reflection

""" Show reflection inside python """
import inspect
import types
 
 
class Test():
    """ A class to inspect """
    def __init__(self, name):
        self.name = name
 
    def show(self):
        """ Show normally """
        print self.name
 
    def special(self, superlative="strong"):
        """ Show with superlative """
        print "<" + superlative + ">", self.name, "</" + superlative + ">"
 
    def combine(self, before="not really", after="after all"):
        """ Show it with start and finish """
        print before, self.name, after
 
t = Test("me")
 
for key, data in inspect.getmembers(t):
    if isinstance(data, types.MethodType):
        spec = inspect.getargspec(data)
        print 'Function:', key, spec.args, spec.defaults, data.__doc__
        if len(spec.args) == 1 or (spec.defaults != None and
                                   len(spec.args) == len(spec.defaults) + 1):
            print "Result:",
            data()
    if key == '__doc__':
        print "Documentation:", data

simple enumerate type

""" Enumeration example """
 
 
def enumValues(tp):
    """ Return defined enumeration values """
    if not hasattr(tp, "values"):
        fillEnum(tp)
    return tp.values
 
 
def fillEnum(tp):
    """ Fill the values structure for this enumerate type """
    tp.values = sorted([
        d for d in tp.__dict__.iteritems() if isinstance(d[1], int)
    ], key=lambda d: d[1])
 
 
def enumValue(tp, nr):
    """ Return the nr value """
    if not hasattr(tp, "values"):
        fillEnum(tp)
    return binary_search(tp.values, nr,
        lambda x, y: -1 if x[1] < y else 1 if x[1] > y else 0)[0]
 
 
def enumOrd(tp, value):
    """ Return the number by the given value """
    try:
        return tp.__dict__[value]
    except KeyError:
        return None
 
 
def binary_search(a, x, compare, lo=0, hi=None):
    """ General binary search algorithm """
    if hi == None:
        hi = len(a)
    while lo < hi:
        mid = (lo + hi) // 2
        midval = a[mid]
        if compare(midval, x) < 0:
            lo = mid + 1
        elif compare(midval, x) > 0:
            hi = mid
        else:
            return a[mid]
    return (None, 0)
 
 
class Days:
    """ Weekdays """
    Monday = 1
    Tuesday = 2
    Wednesday = 3
    Thursday = 4
    Friday = 5
    Saturday = 6
    Sunday = 7
 
 
class Words:
    """ Words """
    Aap = 0
    Noot = 12
    Mies = 200
    Zus = 210
 
print "Constant:", Days.Friday
 
print "List of tuples:"
for day in enumValues(Days):
    print day
 
print "String from number:", enumValue(Days, 5)
print "Number from string:", enumOrd(Days, "Thursday")
print "Unknown string:", enumOrd(Days, "Sunnday")
print "String from number:", enumValue(Words, 12)
print "Unknown number:", enumValue(Words, 112)
Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox