Skip to content

Instantly share code, notes, and snippets.

@conf8o
Created July 20, 2021 04:05
Show Gist options
  • Save conf8o/e4ca0241e2aa7023fe06b4af27ac26c4 to your computer and use it in GitHub Desktop.
Save conf8o/e4ca0241e2aa7023fe06b4af27ac26c4 to your computer and use it in GitHub Desktop.
cond デコレータ
from dataclasses import dataclass
class Cond:
def __init__(self):
self.conditions = []
def add(self, predicate, func):
self.conditions.append((predicate, func))
def call(self, *args, **kwargs):
try:
func = next(f
for p, f
in self.conditions
if p(*args, **kwargs)
)
return func(*args, **kwargs)
except StopIteration:
raise RuntimeError("No condition match")
def cond(self, predicate=lambda _: True):
def _predicate(func):
self.add(predicate, func)
return _predicate
classifier = Cond()
@classifier.cond(lambda file: file.i <= 5 and file.like >= 5)
def ranked(file) -> str:
return "Ranked.{today('yyyy-MM-dd')}"
@classifier.cond(lambda file: file.like >= 5)
def revenging(file) -> str:
return "2.Revenging"
@classifier.cond()
def unranked(file) -> str:
return "Unranked"
@dataclass
class File:
i: int
like: int
f = File(6, 5)
print(classifier.call(f))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment