3 ms·
You could also use a normal class, a direct translation of the Ruby example: @functools.total_ordering class AppVersion: def __init__(self, versi
by pansa2 11mo ago
You could also use a normal class, a direct translation of the Ruby example:
@functools.total_ordering
class AppVersion:
def __init__(self, version_string):
parts = [int(x) for x in str(version_string).split('.')]
self.major, self.minor, self.patch = parts[0] or 0, parts[1] or 0, parts[2] or 0
def __lt__(self, other):
return [self.major, self.minor, self.patch] < [other.major, other.minor, other.patch]
def __eq__(self, other):
return [self.major, self.minor, self.patch] == [other.major, other.minor, other.patch]
def __str__(self):
return f'{self.major}.{self.minor}.{self.patch}'
- js2 11mo agoFWIW, these lines are not equivalent: @major, @minor, @patch = parts[0] || 0, parts[1] || 0, parts[2] || 0 self.major, self.minor, self.patch = parts[0] or 0, parts[1] or 0, parts[2] or 0 The Ruby case is intended to handle strings like "1", "1.2", and "1.2.3". The Python code will throw an IndexError as written. Which is why I did this in the namedtuple example: parts = [int(x) for x in version_string.split(".")] + [0, 0] That ensures you'll have at least three parts so you can then: self.major, self.minor, self.patch = parts[:3]