pyver.py
pyver.py (1833 bytes)
"""
Some surprising ways to test the running Python version ...
Tested in the latest from the each minor series 3.9.21 through 3.15a7
on linux.
```sh
$ for python in 3.9 3.10 3.11 3.12 3.13 3.14 3.15; do uv run --python $python pyver.py; done
your guessed python version is 3.9, actual is 3.9.21
your guessed python version is 3.10, actual is 3.10.16
your guessed python version is 3.11, actual is 3.11.10
your guessed python version is 3.12, actual is 3.12.8
your guessed python version is 3.13, actual is 3.13.12
your guessed python version is 3.14, actual is 3.14.2
your guessed python version is 3.15, actual is 3.15.0a7
```
"""
import sys
import datetime
from math import log
import fractions
class C(datetime.date):
i = 0
def __init__(self, *_):
super().__init__()
type(self).i += 1
def try_call(f, *args, **kw):
try:
f(*args, **kw)
return True
except Exception:
return False
class BigConstant:
def __index__(self):
return 10**1000
def __float__(self):
raise OverflowError
# t1: version is >= 3.10
t1 = frozenset() is not frozenset()
# t2: version is >= 3.11
t2 = len(fractions.Fraction().__reduce__()[1]) == 2
# t3: version is >= 3.12 (this doesn't test what I intended but so what!)
t3 = len((lambda: ~True).__code__.co_code) != 6 and t2
# t4: version is >= 3.13
C.i = 0
C(1, 2, 3).replace(month=9)
t4 = C.i > 1
# t5: version is >= 3.14
t5a = try_call(datetime.time.fromisoformat, "12:33:44,55")
t5b = try_call(datetime.time.fromisoformat, "12,55")
t5 = t5a and not t5b
# t6: version is >= 3.15
t6 = try_call(log, BigConstant())
ver = sys.version.split()[0]
# print(f"{ver:8} {t1:<1} {t2:<1} {t3:<1} {t4:<1} {t5:<1} {t6:<1}")
print(
f"your guessed python version is 3.{sum((9, t1, t2, t3, t4, t5, t6))}, actual is {ver}"
)