I want to write a python code generator, and it would be useful if I had a regular expression that describes all valid python programs.
Is there such a regular expression? What is it?
Such a regular expression cannot exist, because regular expressions are, by definition, not powerful enough to recognize full Turing languages ββ(e.g. python).
If you are creating a line with a snippet of Python code and want to check if it is syntactically correct, try the built-in compile function. It returns a resulting code object or throws a SyntaxError exception.
compile
SyntaxError
You want to lint your code. There are several tools for this with Python; pylint , PyChecker and pyflakes should all do the trick.
To answer your real question: no, this is not a task for regular expressions.