Last active
June 7, 2025 15:29
-
-
Save neutrinoceros/eafa1cbcda6d770f8a2604476994a76a to your computer and use it in GitHub Desktop.
A simple Python class to convert to/from Python versions/hexes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # A custom re-implementation of `sys.hexversion` | |
| # which was a useful exercise to understand how this value is computed | |
| # /// script | |
| # requires-python = ">=3.10" | |
| # dependencies = [] | |
| # /// | |
| from dataclasses import dataclass | |
| from enum import IntEnum | |
| from typing import final, Literal | |
| class Level(IntEnum): | |
| MAJOR = 0x01000000 | |
| MINOR = 0x00010000 | |
| MICRO = 0x00000100 | |
| ALPHA = 0xA0 | |
| BETA = 0xB0 | |
| CANDIDATE = 0xC0 | |
| FINAL = 0xF0 | |
| @final | |
| @dataclass(frozen=True, slots=True) | |
| class PythonVersion: | |
| major: int | |
| minor: int | |
| micro: int | |
| release_level: Literal[Level.ALPHA, Level.BETA, Level.CANDIDATE, Level.FINAL] | |
| serial: int | |
| @classmethod | |
| def from_hex(cls, hex_:str, /) -> PythonVersion: | |
| val = int(hex_, base=16) | |
| major = val >> 24 | |
| val -= major*Level.MAJOR | |
| minor = val >> 16 | |
| val -= minor*Level.MINOR | |
| micro = val >> 8 | |
| val -= micro*Level.MICRO | |
| serial = val % 15 | |
| release_level = Level(val - serial) | |
| return PythonVersion(major, minor, micro, release_level, serial) | |
| def to_hex(self) -> str: | |
| hex_ = hex( | |
| self.major*Level.MAJOR + | |
| self.minor*Level.MINOR + | |
| self.micro*Level.MICRO + | |
| self.release_level + | |
| self.serial | |
| ) | |
| MIN_SIZE = 8 | |
| if len(hex_.removeprefix("0x")) < MIN_SIZE: | |
| return hex_[:2] + hex_[2:].zfill(MIN_SIZE) | |
| else: | |
| return hex_ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment