Commit | Line | Data |
---|---|---|
88d3c3d9 FT |
1 | import operator |
2 | ||
3 | def pfxmatch(pfx, item): | |
4 | return str(item)[:len(pfx)] == pfx | |
5 | ||
6 | def ipfxmatch(pfx, item): | |
7 | return str(item).upper()[:len(pfx)] == pfx.upper() | |
8 | ||
9 | class ambiguous(LookupError): | |
10 | def __init__(self, a, b): | |
11 | super().__init__("ambigous match: %s and %s" % (a, b)) | |
12 | self.a = a | |
13 | self.b = b | |
14 | ||
15 | def find(seq, *, item=None, test=None, match=None, key=None, default=LookupError): | |
16 | if key is None: | |
17 | key = lambda o: o | |
18 | if match is None and item is not None: | |
19 | match = lambda o: test(item, o) | |
20 | if test is None: | |
21 | test = operator.eq | |
22 | found = None | |
23 | for thing in seq: | |
24 | if match(key(thing)): | |
25 | if found is None: | |
26 | found = thing | |
27 | else: | |
28 | if default is LookupError: | |
29 | raise ambiguous(key(found), key(thing)) | |
30 | else: | |
31 | return default | |
32 | if found is not None: | |
33 | return found | |
34 | if default is LookupError: | |
35 | raise LookupError() | |
36 | else: | |
37 | return default |