X-Git-Url: http://dolda2000.com/gitweb/?p=fulbank.git;a=blobdiff_plain;f=fulbank%2Futil.py;fp=fulbank%2Futil.py;h=eaf1249fa0ea0308802169e735421da1e837f50f;hp=0000000000000000000000000000000000000000;hb=88d3c3d9e2b4c5ab6112bc76dbcd8c04244cb177;hpb=be69f65b9fdbb7944b3724cf0ba1e55b9ba66a3e diff --git a/fulbank/util.py b/fulbank/util.py new file mode 100644 index 0000000..eaf1249 --- /dev/null +++ b/fulbank/util.py @@ -0,0 +1,37 @@ +import operator + +def pfxmatch(pfx, item): + return str(item)[:len(pfx)] == pfx + +def ipfxmatch(pfx, item): + return str(item).upper()[:len(pfx)] == pfx.upper() + +class ambiguous(LookupError): + def __init__(self, a, b): + super().__init__("ambigous match: %s and %s" % (a, b)) + self.a = a + self.b = b + +def find(seq, *, item=None, test=None, match=None, key=None, default=LookupError): + if key is None: + key = lambda o: o + if match is None and item is not None: + match = lambda o: test(item, o) + if test is None: + test = operator.eq + found = None + for thing in seq: + if match(key(thing)): + if found is None: + found = thing + else: + if default is LookupError: + raise ambiguous(key(found), key(thing)) + else: + return default + if found is not None: + return found + if default is LookupError: + raise LookupError() + else: + return default