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)
Answer from Duncan on Stack OverflowWhy 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)
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.
Videos
What is the best AI for Python coding?
What is Python?
What is a Python AI code generator?
We use Jinja2 to fill in a template. It's much simpler.
The template looks a lot like Python code with a few {{something}} replacements in it.
This is pretty much the best way to generate Python source code. However, you can also generate Python executable code at runtime using the ast library. You can build code using the abstract syntax tree, then pass it to compile() to compile it into executable code. Then you can use eval() to run the code.
I'm not sure whether there is a convenient way to save the compiled code for use later though (ie. in a .pyc file).