Find actual value of SyntaxError exception python
<p>I'm trying to evaluate python code stored in a string using the ast library, however when accessing the message attribute of the SyntaxException error produced, I can only print the reference to the object and not the actual value. How do I print this value?</p>

<p>Here's the code I'm using:</p>

<pre><code>#!/usr/bin/python

import ast

def is_valid_python(code):
    try:
         ast.parse(code)
    except SyntaxError:
         return str(SyntaxError.message)
    return True

code = 'print("hello"")'

print(is_valid_python(code))
</code></pre>

<p>and the message printed is: </p>

<pre><code>&lt;attribute 'message' of 'exceptions.BaseException' objects&gt;
</code></pre>

<p>You're printing the generic SyntaxError class' message attribute, not the one from the actual exception that was thrown.</p>

<p>Try</p>

<pre><code>except SyntaxError as syntax_error:
    return syntax_error.message
</code></pre>

<p>Note that it's a bit strange to have a function that returns True on success, or a string on failure.</p>

python