Abhijit Ray
Abhijit Ray

Reputation: 105

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.

Upvotes: 2

Views: 3840

Answers (2)

Duncan
Duncan

Reputation: 95652

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)

Upvotes: 3

tobias_k
tobias_k

Reputation: 82899

If you want to do this with code generation, you could just create some template for the function and then use str.format to fill in the parameters from your dictionary.

template = """def func{0}(self):
    ans = ctypes.{1}()
    self.driver.get{0}(ctypes.byref(ans))
    return ans
    """

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

for a, b in funcs.items():
    function = template.format(a, b)
    print function

Just pipe the output to some file, or directly write it to a file instead of printing.

Upvotes: 2

Related Questions