0

I am looking for code to check if a string representing a function header of a function is syntactically correct.

Here is my string example:

'''+'def __init__(self,{arg})'.format(arg = ','.join(i for i in someListOranArgPassedIn), )+''':

If this function was defined as

def __init__(self,,...a,,//b):

and goes against syntactic rules, what can I add to raise an exception?

0

1 Answer 1

-1

Using the function from here.

import ast
def is_valid_python(code):
    try:
        ast.parse(code)
    except SyntaxError:
        return False
    return True

test_args = lambda args: "def init(self, {arg}):\n\tpass".format(arg = ",".join(args))
print is_valid_python(test_args(["a", "b"]))
print is_valid_python(test_args(["", "...a", "", "//b"]))
Sign up to request clarification or add additional context in comments.

3 Comments

Fails on bare return. I suggest you use compile instead of ast.parse.
@Veedrac, I don't follow. Why would a return be a parameter in a function?
is_valid_python("return") gives True; it should give False. Doing a full compile with compile catches this.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.