Compatible Release Operator (~=)
Understand and convert the ~= compatible release operator between requirements.txt and pyproject.toml. Learn how ~=1.4.2 differs from >=1.4.2,<1.5.
Detailed Explanation
The compatible release operator ~= is a shorthand for a version range that allows patch-level or minor-level upgrades while preventing major version changes. It is equivalent to >=V.N, ==V.* where the last component is dropped.
How ~= works:
~=1.4.2is equivalent to>=1.4.2, ==1.4.*(i.e.,>=1.4.2, <1.5.0)~=1.4is equivalent to>=1.4, ==1.*(i.e.,>=1.4, <2.0)~=2.0is equivalent to>=2.0, <3.0
requirements.txt:
django-cors-headers~=4.3
djangorestframework~=3.14
celery~=5.3.0
boto3~=1.28
Converted to pyproject.toml:
[project]
dependencies = [
"django-cors-headers~=4.3",
"djangorestframework~=3.14",
"celery~=5.3.0",
"boto3~=1.28",
]
When to use ~= vs explicit ranges:
The ~= operator is ideal when you trust a package to follow Semantic Versioning (SemVer). It automatically allows bug fixes and minor improvements while protecting against breaking changes. Compared to writing >=4.3,<5.0 manually, ~=4.3 is more concise and semantically clear.
However, not all Python packages follow SemVer strictly. If a package has a history of introducing breaking changes in minor versions, explicit ranges like >=4.3,<4.5 may be safer. Always check the package's changelog policy before choosing.
Use Case
Converting a project that uses ~= compatible release specifiers throughout its requirements, such as an enterprise Python application following SemVer-compatible dependency policies.