Skip to content

Instantly share code, notes, and snippets.

@DavidBuchanan314
Last active December 6, 2024 18:21
Show Gist options
  • Save DavidBuchanan314/0aab1a5b2eae556d88a53df7a91b4fb2 to your computer and use it in GitHub Desktop.
Save DavidBuchanan314/0aab1a5b2eae556d88a53df7a91b4fb2 to your computer and use it in GitHub Desktop.
magically import magic number constants (edit: moved to github https://github.com/DavidBuchanan314/magic-numbers (and pypi(!)))
from magic_numbers import FORTY_TWO, SIXTY_NINE, FOUR_HUNDRED_AND_TWENTY
from magic_numbers import ONE_THOUSAND_THREE_HUNDRED_AND_TWELVE
print(f"{FORTY_TWO = }")
print(f"{SIXTY_NINE = }")
print(f"{FOUR_HUNDRED_AND_TWENTY = }")
print(f"{ONE_THOUSAND_THREE_HUNDRED_AND_TWELVE = }")
import sys
_orig_module = sys.modules[__name__]
# https://stackoverflow.com/a/493788/4454877
def _text2int(textnum: str, numwords={}) -> int | None:
if not numwords:
units = [
"zero", "one", "two", "three", "four", "five", "six", "seven", "eight",
"nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen",
"sixteen", "seventeen", "eighteen", "nineteen",
]
tens = ["", "", "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety"]
scales = ["hundred", "thousand", "million", "billion", "trillion", "quadrillion"]
numwords["and"] = (1, 0)
for idx, word in enumerate(units): numwords[word] = (1, idx)
for idx, word in enumerate(tens): numwords[word] = (1, idx * 10)
for idx, word in enumerate(scales): numwords[word] = (10 ** (idx * 3 or 2), 0)
current = result = 0
for word in textnum.split():
if word not in numwords:
return None
scale, increment = numwords[word]
current = current * scale + increment
if scale > 100:
result += current
current = 0
return result + current
class MagicNumbers:
def __getattribute__(self, name: str) -> int:
if name.startswith("_"): # handle dunders
return object.__getattribute__(_orig_module, name)
val = _text2int(name.lower().replace("_", " "))
if val is None: # should raise an import error
return object.__getattribute__(_orig_module, name)
return val
sys.modules[__name__] = MagicNumbers()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment