Replace long constant names with 2 ASCII characters
pip:
pip install microconst
poetry:
poetry add microconst
Every call of flag or key generates 2-character constant. This constant is represented as left and right indexes of f"{ascii_letters}{digits}" str. Each time the left index reaches cap, it resets to 0 and right index increments.
After reaching both of caps, next call of function will throw OverflowError. Current maximum count of constants is 3844.
key function requires value_type argument, such as str, int etc. This type used in both static analysis and type conversion with Key.parse_entry function.
Main purpose of this library is making telegram bot's "callback_data" much more compact because of 64-byte limit. You can see more realistic example here
Before:
from enum import StrEnum, auto
# Some very strict limit
MAX_LEN: int = 4
class Status(StrEnum):
PENDING = auto()
APPROVED = auto()
REJECTED = auto()
assert Status.PENDING == "pending"
assert len(Status.PENDING) > MAX_LEN # Too longAfter:
from microconst import flag
MAX_LEN: int = 4
# Autogenerates unique pairs of characters
class Status:
PENDING = flag()
APPROVED = flag()
REJECTED = flag()
assert Status.PENDING == "aa"
assert len(Status.PENDING) < MAX_LEN Before:
from enum import StrEnum, auto
class Data(StrEnum):
USERNAME = auto()
ORDER = auto()
# You should use separator because of varying character count in key
username = Data.USERNAME + ":" + "name"
assert username == "username:name" # Too long
value = username.split(":")[1]
assert value == "name"
order = Data.ORDER + ":" + str(1337)
assert order == "order:1337"
# Order doesnt contain its type anywhere, so you should convert types each time
assert int(order.split(":")[1]) == 1337After:
from microconst import key, parse_entry
class Data:
USERNAME = key(str)
ORDER = key(int)
# You can call keys to create key-value pair (acts same as concat)
username = Data.USERNAME("name")
assert username == "aaname"
# Getting value
value = Data.USERNAME.parse_entry(username)
assert value == "name"
order = Data.ORDER(1337)
assert order == "ba1337"
# You can use separate function or method. Method doesnt require type argument
assert parse_entry(order, int) == 1337
assert Data.ORDER.parse_entry(order) == 1337Unique feature, it's hard to implement, so no comprasion before and after:
from microconst import key, parse_entry
class Data:
ORDER = key(Literal[1, 2, 3])
assert Data.ORDER(1) == "aa1"
# assert Data.ORDER(4) == "aa4" # Mypy error
assert Data.ORDER.parse_entry("__3") == 3
# assert Data.ORDER.parse_entry("__10") == 10 # Mypy errorMIT