Skip to content

Instantly share code, notes, and snippets.

@moll-dev
Created November 12, 2024 18:18
Show Gist options
  • Select an option

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

Select an option

Save moll-dev/0ff9f385356470f40355f5c7ccd82193 to your computer and use it in GitHub Desktop.
Magic Values Code
from typing import Optional, List, Type, Dict, Any
class MetaConstant(type):
def __repr__(cls) -> str:
"""Constants' class name with additional context.
Ex. DataCenter -> Location.DataCenter
Ex. fra4 -> DataCenter.fra4("fra4")
Ex. Constant -> Constant
"""
parent = cls.mro()[1]
if parent == object:
return cls.__name__
else:
repr = f"{parent.__name__}.{cls.__name__}"
if hasattr(cls, "_value"):
repr += f'("{cls._value}")'
return repr
class Constant(metaclass=MetaConstant):
_value: str
def __new__(
cls, val: Optional[str] = None, _visited: List[Type] = []
) -> "Constant":
_value: Optional[str] = getattr(cls, "_value", None)
if _value is None and val is None:
msg = f'Abstract {cls.__bases__[0].__name__} "{cls.__name__}" cannot be instantiated'
raise TypeError(msg)
elif _value is None:
# DFS through the class tree to find a matching subclass.
for child in cls.__subclasses__():
try:
if match := child.__new__(child, val, _visited=_visited):
return match
except:
continue
# Compile a list of the subclassese we've tried for a better exception message.
valids = ", ".join([f"{c}" for c in _visited])
msg = f"invalid {cls.__name__}:'{val}' is not valid for any {cls.__name__}s: [{valids}]"
raise ValueError(msg)
elif val is None:
# Default case.
return super(Constant, cls).__new__(cls)
else:
# Base case for DFS.
if _value == val:
return super(Constant, cls).__new__(cls)
else:
_visited.append(cls)
msg = f"invalid value for {cls}: '{val}'"
raise ValueError(msg)
def __init_subclass__(cls) -> None:
"""Register subclass as parent attribute
Ex. Datacenter.fra4
"""
setattr(type(cls), cls.__name__, cls)
@property
def value(self) -> str:
return self._value
def __repr__(self) -> str:
return "Value: "+self._value
def __str__(self) -> str:
return self._value
def __eq__(self, other:Any) -> bool:
return self._value == other._value
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment