Abuse of the object-nature of functions?

Ant antroy at gmail.com
Tue Jul 11 09:45:08 EDT 2006


Hi all,

In a framework I've written to test out website, I use something like
the following to add functionality at various points:

#-----------------------------------
def do_work(callable, data):
    assertion = False
    try:
        assertion = callable.is_assertion
    except:
        pass

    out = callable(data)

    if assertion:
        print "Test " % ("Failed", "Suceeded")[out]

    return out

def get_assn(fn):
    def wrapper(*args, **kw):
        return fn(*args, **kw)
    out = wrapper
    out.is_assertion = True
    return out

def funct(data):
    return True

x = funct
y = get_assn(funct)

do_work(x, data)
do_work(y, data)

#-----------------------------------

The idea is that I can mark some functions as being assertions, and use
the same function for applying the callable to the data and optionally
printing some information. This way I needn't worry whether the
callable is a custom object or a simple function.

The question is, is this a reasonable thing to do? It works, but is it
considered bad practice to add attributes to functions? And are there
any dangers?




More information about the Python-list mailing list