Skip to content

Instantly share code, notes, and snippets.

@moll-dev
Last active November 13, 2024 16:04
Show Gist options
  • Select an option

  • Save moll-dev/0cb0432ef08ae52c37de5720d6f4f142 to your computer and use it in GitHub Desktop.

Select an option

Save moll-dev/0cb0432ef08ae52c37de5720d6f4f142 to your computer and use it in GitHub Desktop.
Magic Values ✨
Display the source blob
Display the rendered blob
Raw
{
"cells": [
{
"cell_type": "code",
"execution_count": 1,
"id": "edc8c846-2741-4bc0-8e88-7115806ec913",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"Version 1.0.5\n"
]
}
],
"source": [
"%load_ext nb_mypy\n",
"\n",
"# Ignore no_redef https://github.com/python/mypy/issues/11065"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "2594d022-6287-432f-9168-f3a4bac89e40",
"metadata": {},
"outputs": [],
"source": [
"from typing import Optional, List, Type, Dict, Any\n",
"\n",
"class MetaConstant(type):\n",
" def __repr__(cls) -> str:\n",
" parent = cls.mro()[1]\n",
" if parent == object:\n",
" return cls.__name__\n",
" else:\n",
" repr = f\"{parent.__name__}.{cls.__name__}\"\n",
" if hasattr(cls, \"_value\"):\n",
" repr += f'(\\'{cls._value}\\')'\n",
" return repr\n",
"\n",
"\n",
"class Constant(metaclass=MetaConstant):\n",
" _value: str\n",
" def __new__(\n",
" cls, val: Optional[str] = None, _visited: Optional[List[Type]] = None\n",
" ) -> \"Constant\":\n",
" if _visited is None:\n",
" _visited = []\n",
" _value: Optional[str] = getattr(cls, \"_value\", None)\n",
" if _value is None and val is None:\n",
" msg = f'Abstract {cls.__bases__[0].__name__} \"{cls.__name__}\" cannot be instantiated'\n",
" raise TypeError(msg)\n",
" elif _value is None:\n",
" # DFS through the class tree to find a matching subclass.\n",
" for child in cls.__subclasses__():\n",
" try:\n",
" if match := child.__new__(child, val, _visited=_visited):\n",
" return match\n",
" except:\n",
" continue\n",
" # Compile a list of the subclassese we've tried for a better exception message.\n",
" valids = \", \".join([f\"{c}\" for c in _visited])\n",
" msg = f\"invalid {cls.__name__}:'{val}' is not valid for any {cls.__name__}s: [{valids}]\"\n",
" raise ValueError(msg)\n",
" elif val is None:\n",
" # Default case.\n",
" return super(Constant, cls).__new__(cls)\n",
" else:\n",
" # Base case for DFS.\n",
" if _value == val:\n",
" return super(Constant, cls).__new__(cls)\n",
" else:\n",
" _visited.append(cls)\n",
" msg = f\"invalid value for {cls}: '{val}'\"\n",
" raise ValueError(msg)\n",
"\n",
" def __init_subclass__(cls) -> None:\n",
" \"\"\"Register subclass as parent attribute\n",
" Ex. Datacenter.fra4\n",
" \"\"\"\n",
" setattr(type(cls), cls.__name__, cls)\n",
"\n",
" @property\n",
" def value(self) -> str:\n",
" return self._value\n",
"\n",
" def __repr__(self) -> str:\n",
" return \"Value: \"+self._value\n",
"\n",
" def __str__(self) -> str:\n",
" return self._value\n",
"\n",
" def __eq__(self, other:Any) -> bool:\n",
" return self._value == other._value\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "ae4f3d1f-ee06-4e8d-b0ef-f9b2f14cb8b3",
"metadata": {},
"outputs": [],
"source": [
"class Location(Constant):\n",
" DataCenter: \"DataCenter\"\n",
" AvailabilityZone: \"AvailabilityZone\"\n",
"\n",
"class DataCenter(Location):\n",
" ams1: \"ams1\"\n",
" lon1: \"lon1\"\n",
"\n",
"class ams1(DataCenter):\n",
" _value = \"ams1\"\n",
"\n",
"class lon1(DataCenter):\n",
" _value = \"lon1\"\n",
"\n",
"class AvailabilityZone(Location):\n",
" west1_a: \"west1_a\"\n",
" west2_a: \"west2_a\"\n",
" \n",
"class west1_a(AvailabilityZone):\n",
" _value = \"west1-a\"\n",
" \n",
"class west2_a(AvailabilityZone):\n",
" _value = \"west2-a\""
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "0689f3c7-b6d5-4103-a522-bf9d717d3787",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"DataCenter.ams1('ams1')"
]
},
"execution_count": 4,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Typed\n",
"ams1"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "a61b74e4-e7d8-4412-b916-3adb20613b8a",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"Value: ams1"
]
},
"execution_count": 5,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Singleton value\n",
"ams1()"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "52a2d6d6-87e5-44cf-871e-22dae46fbc7d",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ams1'"
]
},
"execution_count": 6,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ams1().value"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "bf73bc28-77d0-4127-b29b-ba6595d1e741",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 7,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"ams1() == ams1()"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "1d7ab03c-9cb0-48cf-8478-3b1de3fa3eb7",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"\"My datacenter is ams1=DataCenter.ams1('ams1')\""
]
},
"execution_count": 8,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# REPR, string format works\n",
"f\"My datacenter is {ams1=}\""
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "20e44be6-5a02-44ae-9aac-32198018aa81",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ams1'"
]
},
"execution_count": 9,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Validation\n",
"DataCenter(\"ams1\").value"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "e70ccf70-d3b6-418e-926a-96e59fe93b18",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"'ams1'"
]
},
"execution_count": 10,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"Location(\"ams1\").value"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "061b83a9-68d7-4f9c-a252-3a23a6842d37",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"DataCenter.ams1('ams1')"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(Location(\"ams1\"))"
]
},
{
"cell_type": "code",
"execution_count": 12,
"id": "b0858aad-98b0-4413-97fc-835a0dbba4e6",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"AvailabilityZone.west1_a('west1-a')"
]
},
"execution_count": 12,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(Location(\"west1-a\"))"
]
},
{
"cell_type": "code",
"execution_count": 13,
"id": "31252ddf-da6f-4cbb-b49b-e7fd13d89011",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"invalid DataCenter:'foo1' is not valid for any DataCenters: [DataCenter.ams1('ams1'), DataCenter.lon1('lon1')]\n"
]
}
],
"source": [
"# Free Validation with helpful error messages!\n",
"try:\n",
" DataCenter(\"foo1\")\n",
"except ValueError as e:\n",
" print(e)"
]
},
{
"cell_type": "code",
"execution_count": 17,
"id": "332ba91f-4718-4fac-9d86-4a19f2e86bd7",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"invalid Location:'foo1' is not valid for any Locations: [DataCenter.ams1('ams1'), DataCenter.lon1('lon1'), AvailabilityZone.west1_a('west1-a'), AvailabilityZone.west2_a('west2-a')]\n"
]
}
],
"source": [
"# Free Validation with helpful error messages!\n",
"try:\n",
" Location(\"foo1\")\n",
"except ValueError as e:\n",
" print(e)"
]
},
{
"cell_type": "code",
"execution_count": 14,
"id": "c5244817-7bb1-46cc-a2e7-a2692125cfbc",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 14,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"# Multiple ways to instantiate, type stable output\n",
"Location(\"ams1\") == DataCenter(\"ams1\") == Location.DataCenter.ams1 == DataCenter.ams1 == ams1()"
]
},
{
"cell_type": "code",
"execution_count": 15,
"id": "152b951a-ea0a-43c9-8830-17f04c8c17cb",
"metadata": {},
"outputs": [
{
"data": {
"text/plain": [
"True"
]
},
"execution_count": 15,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"type(Location(\"ams1\")) == type(DataCenter(\"ams1\")) == ams1"
]
},
{
"cell_type": "code",
"execution_count": 16,
"id": "58c332d2-68bf-4b75-9308-04e5c57bc111",
"metadata": {},
"outputs": [],
"source": [
"def print_my_location(location:Location):\n",
" print(location)"
]
},
{
"cell_type": "code",
"execution_count": 18,
"id": "5b17faaf-5a07-4b13-a6b7-32697f82cb9d",
"metadata": {},
"outputs": [
{
"name": "stderr",
"output_type": "stream",
"text": [
"<cell>2: \u001b[1m\u001b[31merror:\u001b[m Argument 1 to \u001b[m\u001b[1m\"print_my_location\"\u001b[m has incompatible type \u001b[m\u001b[1m\"str\"\u001b[m; expected \u001b[m\u001b[1m\"Location\"\u001b[m \u001b[m\u001b[33m[arg-type]\u001b[m\n"
]
}
],
"source": [
"def wrapper(value:str):\n",
" print_my_location(value)"
]
},
{
"cell_type": "code",
"execution_count": 20,
"id": "38877ca9-e64c-4354-9911-651911955e5e",
"metadata": {},
"outputs": [],
"source": [
"from multimethod import multimethod\n",
"\n",
"DOMAIN = \"moll.dev\"\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def generate_vm_name(vmname:str, location:Location):\n",
" raise ValueError(f\"Location '{type(location)}' not supported yet!\")\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def generate_vm_name(vmname:str, location:DataCenter) -> str:\n",
" print(type(location))\n",
" return f\"{vmname}.{location}.{DOMAIN}\" "
]
},
{
"cell_type": "code",
"execution_count": 21,
"id": "db8fd44f-bc75-4b99-8892-34dce44394c9",
"metadata": {
"jupyter": {
"source_hidden": true
}
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"DataCenter.ams1('ams1')\n"
]
},
{
"data": {
"text/plain": [
"'test1-vm.ams1.moll.dev'"
]
},
"execution_count": 21,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"generate_vm_name(\"test1-vm\", Location(\"ams1\"))"
]
},
{
"cell_type": "code",
"execution_count": 22,
"id": "4a6951ac-e7ae-42c0-b54a-093bd79cd40d",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Got exception >>> Location 'AvailabilityZone.west2_a('west2-a')' not supported yet!\n"
]
}
],
"source": [
"try:\n",
" generate_vm_name(\"test1-vm\", Location(\"west2-a\"))\n",
"except ValueError as e:\n",
" print(f\"Got exception >>> {e}\")"
]
},
{
"cell_type": "code",
"execution_count": 24,
"id": "a1f9d497-3513-4d5c-b01c-b173b564b5f6",
"metadata": {},
"outputs": [],
"source": [
"@multimethod\n",
"def generate_vm_name(vmname:str, location:AvailabilityZone) -> str:\n",
" print(type(location))\n",
" return f\"{vmname}-{location}.{DOMAIN}\""
]
},
{
"cell_type": "code",
"execution_count": 25,
"id": "6845466c-9433-4d67-a3b0-688f837b80fd",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"AvailabilityZone.west2_a('west2-a')\n"
]
},
{
"data": {
"text/plain": [
"'test1-vm-west2-a.moll.dev'"
]
},
"execution_count": 25,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"generate_vm_name(\"test1-vm\", Location(\"west2-a\"))"
]
},
{
"cell_type": "code",
"execution_count": 26,
"id": "79e3298c-9770-4e5b-b1e8-0f0625584627",
"metadata": {},
"outputs": [],
"source": [
"class Environment(Constant):\n",
" Prod:\"Prod\"\n",
" Dev:\"Dev\"\n",
" PCC:\"PCC\"\n",
" \n",
"class Prod(Environment):\n",
" _value = \"prod\"\n",
"\n",
"class Dev(Environment):\n",
" _value = \"dev\"\n",
"\n",
"class PCC(Environment):\n",
" _value = \"pcc\""
]
},
{
"cell_type": "markdown",
"id": "26c8465a-1f7b-4d26-a09b-e8fa499681b7",
"metadata": {},
"source": [
"| ↓env \\ location → | lon1 | ams1 | west1-a | west2-a |\n",
"| ----------------- | ---- | ---- | ------- | ------- |\n",
"| prod | ✅ | ✅ | ✅ | ✅ |\n",
"| dev | ❌ | ❌ | ✅ | ✅ |\n",
"| pcc | ❌ | ✅ | ❌ | ❌ |"
]
},
{
"cell_type": "code",
"execution_count": 28,
"id": "f1902d58-3284-4cf5-b24d-4d8378b1cd79",
"metadata": {},
"outputs": [],
"source": [
"@multimethod # type: ignore[no-redef]\n",
"def check(environment:Environment, location:Location):\n",
" # log f\"Not a supported deployment combination ({environment}, {location})!\"\n",
" return False\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def check(environment:Prod, location:Location):\n",
" return True\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def check(environment:Dev, location:AvailabilityZone):\n",
" return True\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def check(environment:Dev, location:AvailabilityZone):\n",
" return True\n",
"\n",
"@multimethod # type: ignore[no-redef]\n",
"def check(environment:PCC, location:ams1):\n",
" return True"
]
},
{
"cell_type": "code",
"execution_count": 29,
"id": "88f68c3f-44ce-467d-98b4-4d75133fda13",
"metadata": {},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"\tlon1\tams1\twest1-a\twest2-a\n",
"prod\t✅\t✅\t✅\t✅\t\n",
"dev\t❌\t❌\t✅\t✅\t\n",
"pcc\t❌\t✅\t❌\t❌\t\n"
]
}
],
"source": [
"environments = [Prod(), Dev(), PCC()]\n",
"locations = [lon1(), ams1(), west1_a(), west2_a()]\n",
"\n",
"print(f\"\\t{'\\t'.join([str(l) for l in locations])}\")\n",
"for environment in environments:\n",
" print(environment, end=\"\\t\")\n",
" for location in locations:\n",
" val = \"✅\" if check(environment, location) else \"❌\"\n",
" print(val, end=\"\\t\")\n",
" print()"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "08041963-2f50-460c-a1db-522dc8d5866a",
"metadata": {},
"outputs": [],
"source": []
},
{
"cell_type": "code",
"execution_count": null,
"id": "d5fd0d08-fbc0-4605-9750-52bbfa8ef15f",
"metadata": {
"collapsed": true,
"jupyter": {
"outputs_hidden": true
}
},
"outputs": [],
"source": []
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3 (ipykernel)",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.0"
}
},
"nbformat": 4,
"nbformat_minor": 5
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment