Python's context-sensitive grammar makes it a particularly unsuitable target for text-based generation of code in this manner. If you continue with this project I expect you will find you get far better results from generating ASTs or choosing a language with a simple grammar in which most possible compositions of tokens are valid.