Mar-16-2020, 12:32 PM
Using compile() is more robust that exec()
>>> source = "def spam(ham=[n for n in range(1, dividend+1) if dividend % n == 0]):\n" >>> source = source.rstrip('\n') + 'pass\n' >>> result = compile(source, '<string>', mode='single') <code object <module> at 0x7f33bbb89420, file "<string>", line 1>Now with an invalid line
>>> source = "def spam(**ham, *eggs):\n" >>> source = source.rstrip('\n') + 'pass\n' >>> result = compile(source, '<string>', mode='single') Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<string>", line 1 def spam(**ham, *eggs):pass ^ SyntaxError: invalid syntax