|
| 1 | +from functools import partial |
| 2 | + |
| 3 | + |
| 4 | +class ReplaceContext: |
| 5 | + __slots__ = ("res", "shouldStop", "count") |
| 6 | + |
| 7 | + def __init__(self, res, count=0, shouldStop=False): |
| 8 | + self.res = res |
| 9 | + self.shouldStop = shouldStop |
| 10 | + self.count = count |
| 11 | + |
| 12 | + |
| 13 | +class SingleURIReplacer: |
| 14 | + def __init__(self, arg): |
| 15 | + raise NotImplementedError |
| 16 | + |
| 17 | + def __call__(self, ctx): |
| 18 | + raise NotImplementedError |
| 19 | + |
| 20 | + |
| 21 | +class CombinedReplacer(SingleURIReplacer): |
| 22 | + __slots__ = ("children",) |
| 23 | + |
| 24 | + def __init__(self, children): |
| 25 | + self.children = children |
| 26 | + |
| 27 | + def __call__(self, ctx): |
| 28 | + for r in self.children: |
| 29 | + r(ctx) |
| 30 | + if ctx.shouldStop: |
| 31 | + break |
| 32 | + return ctx |
| 33 | + |
| 34 | + |
| 35 | +class CombinedReplacerFactory: |
| 36 | + __slots__ = ("args2Ctors", "ctor") |
| 37 | + |
| 38 | + def __init__(self, args2Ctors): |
| 39 | + self.args2Ctors = args2Ctors |
| 40 | + |
| 41 | + def _gen_replacers(self, kwargs): |
| 42 | + for k, v in kwargs.items(): |
| 43 | + c = self.args2Ctors.get(k, None) |
| 44 | + if c: |
| 45 | + yield c(v) |
| 46 | + |
| 47 | + def __call__(self, **kwargs): |
| 48 | + return CombinedReplacer(tuple(self._gen_replacers(kwargs))) |
0 commit comments