|
| 1 | +import re |
| 2 | +from functools import total_ordering |
| 3 | +from typing import Union, List |
| 4 | + |
| 5 | + |
| 6 | +@total_ordering |
| 7 | +class LooseVersion: |
| 8 | + """ |
| 9 | + A flexible version comparison class that handles arbitrary version strings. |
| 10 | + Compares numeric components numerically and alphabetic components lexically. |
| 11 | + """ |
| 12 | + |
| 13 | + _component_re = re.compile(r'(\d+|[a-z]+|\.)', re.IGNORECASE) |
| 14 | + |
| 15 | + def __init__(self, vstring: str): |
| 16 | + self.vstring = str(vstring) |
| 17 | + self.version = self._parse(self.vstring) |
| 18 | + |
| 19 | + def _parse(self, vstring: str) -> List[Union[int, str]]: |
| 20 | + """Parse version string into comparable components.""" |
| 21 | + components = [] |
| 22 | + for match in self._component_re.finditer(vstring.lower()): |
| 23 | + component = match.group() |
| 24 | + if component != '.': |
| 25 | + # Try to convert to int, fall back to string |
| 26 | + try: |
| 27 | + components.append(int(component)) |
| 28 | + except ValueError: |
| 29 | + components.append(component) |
| 30 | + return components |
| 31 | + |
| 32 | + def __str__(self) -> str: |
| 33 | + return self.vstring |
| 34 | + |
| 35 | + def __repr__(self) -> str: |
| 36 | + return f"{self.__class__.__name__}('{self.vstring}')" |
| 37 | + |
| 38 | + def __eq__(self, other) -> bool: |
| 39 | + if not isinstance(other, LooseVersion): |
| 40 | + other = LooseVersion(str(other)) |
| 41 | + return self.version == other.version |
| 42 | + |
| 43 | + def __lt__(self, other) -> bool: |
| 44 | + if not isinstance(other, LooseVersion): |
| 45 | + other = LooseVersion(str(other)) |
| 46 | + return self.version < other.version |
| 47 | + |
| 48 | + def __hash__(self) -> int: |
| 49 | + return hash(tuple(self.version)) |
0 commit comments