0

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...

3
  • Can you give an example of non-code that returns True. Commented Oct 4, 2016 at 4:51
  • >>> is_valid('test') Code is ok. True Commented Oct 4, 2016 at 4:56
  • 4
    That's valid code - an identifier. Commented Oct 4, 2016 at 4:57

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

6 Comments

Thanks! Ill fix it by throwing NameError then
@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?
@MaxLunar I think you have a misunderstanding here. Is x + 1 valid code?
Hm, If i send message that tell user that his variable wasnt defined yet if NameError is raised...
@MaxLunar Why? What if x is not defined? Or if x is a string?
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.