32. A Comparable Version Class
Difficulty: Medium · Topic: OOP & classes
Write a class Version("1.10.2") for dotted version numbers that behaves like a value:
- Comparisons (
== < <= > >=) are numeric, part by part:1.10.0 > 1.9.9. Missing parts count as 0, soVersion("1.2") == Version("1.2.0"). - Equal versions have equal hashes, so they work in sets and as dict keys.
str(v)is the text it was created from;repr(v)isVersion('1.2.0').- Comparing with something that is not a
Versionis never equal (and does not raise for==). - Text with a part that is not a whole number raises
ValueError.
Your code runs in CPython on our servers against 6 tests, including hidden ones.
Sample test
(Version('1.10.0') > Version('1.9.9'), Version('2.0') >= Version('2'), Version('0.9') < Version('0.10'))Expected: (True, True, True)
Hints
Hint 1
Turn the text into a tuple of ints, then drop trailing zeros: tuples already compare part by part.Hint 2
@functools.total_ordering fills in the other comparisons from __eq__ and __lt__.Hint 3
Defining__eq__ sets __hash__ to None: define __hash__ on the same normalised tuple. Return NotImplemented for other types.Learn the concepts
- Sorting with key functions · 5 min read. Tuple keys, mixed directions, stability and data with None in it.
- Classes, properties and dataclasses · 4 min read. Invariants, validated and read-only attributes, alternate constructors and record types.
- Dunder methods and abstract classes · 7 min read. Equality, ordering and hashing that agree, NotImplemented, and interfaces with abc.
More Python problems
- Bank Account with Validation · Easy
- Temperature with Properties · Easy
- Build Records from CSV Rows · Medium
- An Abstract Connector Class · Medium
- LRU Cache · Hard
- A Transaction Context Manager · Hard