Use ast.parse
:
import ast
def is_valid_python(code):
try:
ast.parse(code)
except SyntaxError:
return False
return True
>>> is_valid_python('1 // 2')
True
>>> is_valid_python('1 /// 2')
False
More Related Contents:
- Can someone please tell me why the two python codes below produce entirely different outcomes?
- What does a b prefix before a python string mean?
- Python Script returns unintended “None” after execution of a function [duplicate]
- Python “raise from” usage
- Python print statement “Syntax Error: invalid syntax” [duplicate]
- Is doing multiplication multiple times or assigning to a variable faster?
- How do I create a scoring system in Python? [closed]
- How to end a python program without it going to the next line of code [duplicate]
- What is an alternative to execfile in Python 3?
- Behavior of exec function in Python 2 and Python 3
- Remove and Replace Printed items [duplicate]
- jumping too fast?
- How to get local variables updated, when using the `exec` call?
- Transform a set of numbers in numpy so that each number gets converted into a number of other numbers which are less than it
- Python integer incrementing with ++ [duplicate]
- How to activate virtualenv in Linux?
- How to fix AttributeError: partially initialized module?
- How to use values stored in variables as case patterns?
- Floor division with negative number
- Python and Windows Named Pipes
- Resolving metaclass conflicts
- Nested dictionary comprehension python
- Add Legend to Seaborn point plot
- What’s the best way to store a phone number in Django models?
- How to fix “could not find or load the Qt platform plugin windows” while using Matplotlib in PyCharm
- How can I run an async function using the schedule library?
- How to create a Python dictionary with double quotes as default quote format?
- asyncio.ensure_future vs. BaseEventLoop.create_task vs. simple coroutine?
- How to compute jaccard similarity from a pandas dataframe
- Which of the 4 ways to call super() in Python 3 to use?