I am currently deploying some code on a fleet of raspberry pi systems. The systems all have python 3.7.x installed but one of my team's custom libraries has some python 3.8 features (a few walrus operators, etc). I need to modify my library to remove all of the 3.8 features so that the code runs on these machines. I am not able to update the python version on them. Is there a script or tool that exists to batch check if a file or folder of files is compatible with python 3.7? I'm thinking something similar to how flake8 or black can check for issues.
CodePudding user response:
Run a static analysis tool, like pylint
or mypy
, and make sure that it's running on the appropriate version of Python. One of the first things these tools do is parse the code using the Python parser, and they'll report any SyntaxErrors they find.
CodePudding user response:
From my admittedly light research, there doesn't seem to be a tool specifically built for that. So I will tell you three ways to find out.
1. Just run it
I guess one way would be to just run it and check for errors. This is the most obvious way to do it. But that would be somewhat impractical. You need to check a massive amount of files. So this way might not work for you. I tried this with a test file, and here are the errors if I run it in Python 3.7:
File "test.py", line 3
def cool_function(a, b, /):
^
SyntaxError: invalid syntax
You might notice that there are many 3.8 features used in this file, and those don't show up.
2. Just compile it
Well, you're in luck! If you didn't know already, Python is technically a compiled programming language. It compiles first to bytecode, then runs it.
You can actually compile Python without running it! You can use the py_compile
tool for this! You can use it like this:
python -m py_compile fileA.py fileB.py fileC.py
Unfortunately, this has the same problem as the above other solution. It will stop after finding one error. But it could be good if you want to slowly port these scripts, going error by error.
3. (Potentially) the tool
You can use Pylint for this purpose. If you use the --py-version
flag, you can set the version you want to check compatibility for. You can also use Flake8 for this, but you can't use that flag. You will have to install Pylint with the version of python you want to check for.