by lysecret · 3y ago · 0 comments
class Food:
def __init__(self, temp):
if str(temp).lower().strip() in ['hot', 'warm', 'cold']:
self.temp = temp.lower().strip()
else:
try:
temp_int = int(temp)
if temp_int > 120:
self.temp = 'hot'
elif temp_int < 60:
self.temp = 'cold'
else:
self.temp = 'warm'
except ValueError:
raise ValueError(f'temp must be a number or one of the following: "hot" "warm" "cold", received: {temp}')This is a based on code I have in my editor right now. Typing straight into the comment box so it might be wrong.
Toy = Literal['toy']
class Spec(BaseModel):
sample_size = Union[float, Toy]
def __post_init__(self):
self.sample_size = 0.1 if self.sample_size == 'toy' else self.sample_size import dataclasses
from typing import Literal
@dataclasses.dataclass
class Food:
temp: Literal["hot", "cold", "warm"] = dataclasses.field(init=False)
temp_arg: dataclasses.InitVar[str | int]
def __post_init__(self, temp_arg):
# optional bonus, get the list of temps from the annotation at runtime
# possible_temps = self.__annotations__["temp"].__args__
if str(temp_arg).lower().strip() in ["hot", "warm", "cold"]:
self.temp = temp_arg.lower().strip()
else:
try:
temp_int = int(temp_arg)
if temp_int > 120:
self.temp = "hot"
elif temp_int < 60:
self.temp = "cold"
else:
self.temp = "warm"
except ValueError:
raise ValueError(
f"temp must be a number or one of the "
f'following: "hot" "warm" "cold", received: {temp_arg}'
)