requirements.txt: any version < 1.5 (incl dev and rc versions)

Question:

I am looking for a pattern for Python’s requirement.txt (for usage with pip and python 3.10), which will cover all versions available up to a version 1.5, e.g.

  • 1.4.2.dev5+g470a8b8
  • 1.4.dev22+g2be722f
  • 1.4
  • 1.4rc0
  • 1.5rc1

And: is there a clever way to test this without actually running "pip install" in a fresh venv?

Asked By: herrjeh42

||

Answers:

You should be able to test with python -m pip install --dry-run without actually installing anything.

You can also install and test with packaging which is the library used by pip internally.

I guess !=1.5,<=1.5 should be what you want.

import packaging.specifiers
import packaging.version

version_strings = [
    '1',
    '1.0'
    '1.1',
    '1.4',
    '1.4.2',
    '1.4.2.dev5+g470a8b8',
    '1.4.dev22+g2be722f',
    '1.4',
    '1.4rc0',
    '1.5rc1',
    '1.5',
    '1.5.1',
    '1.6',
    '2',
    '2.0',
]

versions = [packaging.version.Version(v) for v in version_strings]

specifier = packaging.specifiers.SpecifierSet('!=1.5,<=1.5', prereleases=True)

for version in versions:
    print(f'{version} in {specifier}: {version in specifier}')
$ python test.py 
1 in !=1.5,<=1.5: True
1.1.1 in !=1.5,<=1.5: True
1.4 in !=1.5,<=1.5: True
1.4.2 in !=1.5,<=1.5: True
1.4.2.dev5+g470a8b8 in !=1.5,<=1.5: True
1.4.dev22+g2be722f in !=1.5,<=1.5: True
1.4 in !=1.5,<=1.5: True
1.4rc0 in !=1.5,<=1.5: True
1.5rc1 in !=1.5,<=1.5: True
1.5 in !=1.5,<=1.5: False
1.5.post0 in !=1.5,<=1.5: False
1.5.0 in !=1.5,<=1.5: False
1.5.1 in !=1.5,<=1.5: False
1.6 in !=1.5,<=1.5: False
2 in !=1.5,<=1.5: False
2.0 in !=1.5,<=1.5: False

So you could use it like this:

python -m pip install --pre 'somepackage!=1.5,<=1.5'

or in a requirements.txt file:

--pre

somepackage !=1.5, <=1.5

Related:

Answered By: sinoroc
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.