🐜 abbrev
: Expand abbreviations 🐜
Handy when the user has a choice of commands with long names.
Example 1: Use a list of choices
import abbrev
a = ['one', 'two', 'three']
assert abbrev(a, 'one') == 'one'
assert abbrev(a, 'o') == 'one'
assert abbrev(a, 'tw') == 'two'
abbrev(a, 'four') # Raises a KeyError: no such key
abbrev(a, 't') # Raises a KeyError: ambiguous key ('two' or 'three'?)
Example 2: Use a dictionary of choices
import abbrev
d = {'one': 100, 'two': 200, 'three': 300}
assert abbrev(d, 'one') == 100
assert abbrev(d, 'o') == 100
assert abbrev(d, 'tw') == 200
Example 3: Make an abbreviator to re-use
import abbrev
d = {'one': 100, 'two': 200, 'three': 300}
abbreviator = abbrev(d)
assert abbreviator('one') == my_abbrevs('o') == 100
assert abbreviator('tw') == 200
Example 4: Get all matches, when multi=True
import abbrev
a = ['one', 'two, 'three'}
multi = abbrev(a, multi=True) # Make an abbreviator
assert multi('t') == abbrev(d, 't', multi=True) == ('two', three')
assert multi('o') == abbrev(d, 'o', multi=True) == ('one', )
multi('four') # Still raises a key error
Example 5: Get only the first result, when unique=False
import abbrev
d = {'one': 100, 'two': 200, 'three': 300}
assert abbrev(d, 't', unique=False) == (200, 300)
API Documentation
abbrev(abbrevs, key=None, default=NONE, multi=False, unique=True)
Returns:
Type | Description |
---|---|
Any
|
An exapanded abbreviation if |
Parameters:
Name | Type | Description | Default |
---|---|---|---|
abbrevs |
Union[Mapping[str, Any], Sequence[str]]
|
A dictionary with string keys or a sequence of strings |
required |
key |
Optional[str]
|
An abbreviated key to look up in If |
None
|
default |
Any
|
if If |
NONE
|
multi |
bool
|
If True, a tuple of matching keys is returned on a match. If False, the default, only a single matching value is returned |
False
|
unique |
bool
|
If True, the default, If False,
|
True
|
Source code in abbrev/abbrev.py
74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 |
|