Is there a way in Python to either ``type'' functions or for functions to
inherit test suites? I am doing some work evaluating several different
implementations of different functions with various criteria (for
example I may evaluate different sort functions based on speed for the
array size and memory requirements). And I
want to be able to automate the testing of the functions. So I would
like a way to identify a function as being an implementation of
a certain operator so that the test suite can just grab all functions
that are implementation of that operator and run them through the
tests.
My initial thought was to use classes and subclasses, but the class
syntax is a bit finnicky for this purpose because I would first have
to create an instance of the class before I could call it as a
function... that is unless there is a way to allow init to return
a type other than None.
Can metaclasses or objects be used in this fashion?
解决方案
Functions are first class objects in Python and you can treat them as such, e.g. add some metadata via setattr:
>>> def function1(a):
... return 1
...
>>> type(function1)
>>> setattr(function1, 'mytype', 'F1')
>>> function1.mytype
'F1'
Or the same using a simple parametrized decorator:
def mytype(t):
def decorator(f):
f.mytype = t
return f
return decorator
@mytype('F2')
def function2(a, b, c):
return 2