Wrapper around the C extension to provide a consistent API.
| 17 | else: |
| 18 | |
| 19 | class BPlusTreeMap(_c_ext.BPlusTree): |
| 20 | """Wrapper around the C extension to provide a consistent API.""" |
| 21 | |
| 22 | def __init__(self, capacity=None): |
| 23 | """Initialize BPlusTreeMap with optional capacity.""" |
| 24 | if capacity is None: |
| 25 | super().__init__() |
| 26 | else: |
| 27 | super().__init__(capacity=capacity) |
| 28 | |
| 29 | def get(self, key, default=None): |
| 30 | """Get value with default.""" |
| 31 | try: |
| 32 | return self[key] |
| 33 | except KeyError: |
| 34 | return default |
| 35 | |
| 36 | def values(self): |
| 37 | """Return iterator over values.""" |
| 38 | for key, value in self.items(): |
| 39 | yield value |
| 40 | |
| 41 | def clear(self): |
| 42 | """Remove all items from the tree.""" |
| 43 | # C extension doesn't have clear method, so remove keys one by one |
| 44 | # Use while loop to avoid issues with iterator invalidation |
| 45 | while len(self) > 0: |
| 46 | # Get first key and delete it |
| 47 | for key in self.keys(): |
| 48 | del self[key] |
| 49 | break |
| 50 | |
| 51 | def pop(self, key, *args): |
| 52 | """Remove and return value for key with optional default.""" |
| 53 | if len(args) > 1: |
| 54 | raise TypeError( |
| 55 | f"pop expected at most 2 arguments, got {len(args) + 1}" |
| 56 | ) |
| 57 | try: |
| 58 | value = self[key] |
| 59 | del self[key] |
| 60 | return value |
| 61 | except KeyError: |
| 62 | if args: |
| 63 | return args[0] |
| 64 | raise |
| 65 | |
| 66 | def popitem(self): |
| 67 | """Remove and return an arbitrary (key, value) pair.""" |
| 68 | try: |
| 69 | # Get the first key-value pair |
| 70 | for key, value in self.items(): |
| 71 | del self[key] |
| 72 | return (key, value) |
| 73 | except: |
| 74 | pass |
| 75 | raise KeyError("popitem(): tree is empty") |
| 76 |
no outgoing calls