php-version-compare

A simple Python library for comparing “PHP-style” version strings using the rules of PHP’s version_compare function.

Installation

To install the latest release of the library from PyPI, run:

pip install php-version-compare

Alternatively, to install the latest development version directly from the Git repository:

pip install git+https://github.com/marcfrederick/php-version-compare

API Reference

This section contains automatically generated reference documentation from the project’s docstrings.

php_version_compare.canonicalize_version(version)[source]

Canonicalize a version string into a “PHP-style” version string. This function is used to normalize version strings before comparing them.

Examples

>>> canonicalize_version("1.0")
'1.0'
>>> canonicalize_version("1.0-DEV")
'1.0.DEV'
>>> canonicalize_version("1.0.1alpha")
'1.0.1.alpha'
Parameters:

version (str) – The version string to canonicalize.

Returns:

The canonicalized version string.

Return type:

str

php_version_compare.version_compare(version1, version2, operator=None)[source]

Compare two version strings according to PHP’s version_compare function.

Examples

>>> version_compare("1.0", "1.0")
0
>>> version_compare("1.0", "1.1")
-1
>>> version_compare("1.0-pl1", "1.0")
1
>>> version_compare("1.0", "1.0", "==")
True
>>> version_compare("1.0", "1.1", "<")
True
>>> version_compare("1.0", "1.1", ">")
False
Parameters:
  • version1 (str) – The first version string.

  • version2 (str) – The second version string.

  • operator (Literal['<', 'lt', '<=', 'le', '>', 'gt', '>=', 'ge', '==', '=', 'eq', '!=', '<>', 'ne'] | None) – The (optional) comparison operator. Must be one of “<”, “lt”, “<=”, “le”, “>”, “gt”, “>=”, “ge”, “==”, “=”, “eq”, “!=”, “<>”, or “ne”.

Returns:

If operator is None, returns -1 if version1 is less than version2, 0 if they are equal, and 1 if version1 is greater than version2. If operator is provided, returns True if the comparison is true, and False otherwise.

Return type:

Literal[-1, 0, 1] | bool

Versioning

This project follows Semantic Versioning. You can find all available versions on the releases page.

To check the installed version programmatically:

import php_version_compare
print(php_version_compare.__version__)

License

This project is licensed under either of the following, at your option:

Contributions are welcome under the same terms.

Contributing

When contributing, you agree to license your contributions under both the Apache and MIT licenses.