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?

dilbert
  • 2,818
  • 1
  • 25
  • 33

1 Answers1

-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"]))
Community
  • 1
  • 1
dilbert
  • 2,818
  • 1
  • 25
  • 33