Search code examples
pythoncode-generation

Automatic code generation in python


I need to call functions in a C dll from python. So I need to write functions of the format

def funcA(self):
    ans = ctypes.uint64()
    self.driver.getA(ctypes.byref(ans))
    return ans

now I have to write the same code about 30 times, the only difference in each being the name of function called funcA , funcB , funcC and similarly the dll function getA, getB, getC and the type of the return values which can vary

typically I could like to just have a dict

funcs = { 'A':'uint64', 'B':'bool'}

and automatically generate functins

funcA and funcB , with almost the same structure as shown on top , except for the types and the variable names. I would guess there would be some libraries for it.


Solution

  • Why use strings rather than the types themselves?

    funcs = { 'A':ctypes.uint64, 'B':bool }
    

    Then:

    def make_func(name, ctype):
        def func(self):
            ans = ctype()
            getattr(self.driver, 'get'+name)(ctypes.byref(ans))
            return ans
       func.__name__ = 'func'+name
       return func
    
    for a, b in funcs.items():
        globals()['func'+a] = make_func(a, b)
    

    Or ditch the dict and for loop and:

    funcA = make_func('A', ctypes.uint64)
    funcB = make_func('B', bool)