Tool to determine what lowest version of Python required?

Question:

Is there something similar to Pylint, that will look at a Python script (or run it), and determine which version of Python each line (or function) requires?

For example, theoretical usage:

$ magic_tool <EOF
with something:
    pass
EOF
1: 'with' statement requires Python 2.6 or greater

$ magic_tool <EOF
class Something:
    @classmethod
    def blah(cls):
        pass
EOF
2: classmethod requires Python 2.2 or greater
$ magic_tool <EOF
print """Test
"""
EOF
1: Triple-quote requires Python 1.5 of later

Is such a thing possible? I suppose the simplest way would be to have all Python versions on disc, run the script with each one and see what errors occur..

Asked By: dbr

||

Answers:

Not an actual useful answer but here it goes anyway.
I think this should be doable to make (though probably quite an exercise), for example you could make sure you have all the official grammars for the versions you want to check, like this one .

Then parse the bit of code starting with the first grammar version.
Next you need a similar map of all the built-in module namespaces and parse the code again starting with the earliest version, though it might be tricky to differentiate between built-in modules and modules that are external or something in between like ElementTree.

The result should be an overview of versions that support the syntax of the code and an overview of the modules and which version (if at all) is needed to use it. With that result you could calculate the best lowest and highest version.

Answered By: Martin P. Hellwig

Inspired by this excellent question, I recently put together a script that tries to do this. You can find it on github at pyqver.

It’s reasonably complete but there are some aspects that are not yet handled (as mentioned in the README file). Feel free to fork and improve it!

Answered By: Greg Hewgill

The tool pyqver from Greg Hewgill wasn’t updated since a while.

vermin is a similar utility which shows in the verbose mode (-vvv) what lines are considered in the decision.

% pip install vermin
% vermin -vvv somescript.py
Detecting python files..
Analyzing using 8 processes..
!2, 3.6      /path/to/somescript.py
  L13: f-strings require 3.6+
  L14: f-strings require 3.6+
  L15: f-strings require 3.6+
  L16: f-strings require 3.6+
  print(expr) requires 2+ or 3+

Minimum required versions: 3.6
Incompatible versions:     2

Bonus: With the parameter -t=V you can define a target version V you want to be compatible with. If this version requirement is not met, the script will exit with an exit code 1, making it easy integratable into a test suite.

Answered By: Samuel
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.