Join the Stack Overflow Community
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.
Join them; it only takes a minute:
Sign up

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 stdout to code sender. I have implemented anything but code checker.

import ast

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

is_valid() always return True regardless of what comes in. Im really confused...

share|improve this question
    
Can you give an example of non-code that returns True. – AChampion 18 hours ago
    
>>> is_valid('test') Code is ok. True – MaxLunar 18 hours ago
4  
That's valid code - an identifier. – AChampion 18 hours ago
up vote 1 down vote accepted

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

test

is valid code. Even though this statement will throw a NameError 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.

share|improve this answer
    
Thanks! Ill fix it by throwing NameError then – MaxLunar 18 hours ago
1  
@MaxLunar you can't throw a NameError, because how would you know that the user's code is using a variable that wasn't assigned a value? – self 18 hours ago
    
@MaxLunar I think you have a misunderstanding here. Is x + 1 valid code? – Noufal Ibrahim 18 hours ago
    
Hm, If i send message that tell user that his variable wasnt defined yet if NameError is raised... – MaxLunar 18 hours ago
    
@Noufal Ibrahim x + 1 is valid code – MaxLunar 18 hours ago

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.