lines = [] lines.append('def print_success():') lines.append(' print "sucesss"') "\n".join(lines)
If you are building something complex dynamically:
class CodeBlock(): def __init__(self, head, block): self.head = head self.block = block def __str__(self, indent=""): result = indent + self.head + ":\n" indent += " " for block in self.block: if isinstance(block, CodeBlock): result += block.__str__(indent) else: result += indent + block + "\n" return result
You can add additional methods, add new lines to the block and all that, but I think you get the idea.
Example:
ifblock = CodeBlock('if x>0', ['print x', 'print "Finished."']) block = CodeBlock('def print_success(x)', [ifblock, 'print "Def finished"']) print block
Conclusion:
def print_success(x): if x>0: print x print "Finished." print "Def finished."
source share