Checking if string contains valid Python code
<p>I am writing some sort of simple web-interpreter for vk.com . I look for messages, check if they are valid Python code, and then I want to execute that code, and return any <code>stdout</code> to code sender. I have implemented anything but code checker.</p>

<pre><code>import ast

def is_valid(code): 
    try:
        ast.parse(code)
    except SyntaxError:
        print('Input isnt code.')
        return False
    print('Code is ok.')
    return True
</code></pre>

<p><code>is_valid()</code> always return <code>True</code> regardless of what comes in. Im really confused... </p>

<p>Keep in mind, the difference between a runtime error and a parser error is significant in your case and example. The statement:</p>

<pre><code>test
</code></pre>

<p>is <em>valid</em> code. Even though this statement will throw a <code>NameError</code> when the Python VM executes the code, the parser will not know that it actually wasn't assigned a value before the statement is parsed, so that's why it's a runtime error, and not a syntax error.</p>

python