-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstrfmt.py
300 lines (244 loc) · 7.57 KB
/
strfmt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
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
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
import sys
from coolections import subdict
from magic import magic
class SafeSub(dict):
"""Use with str.format_map to leave missing keys untouched.
>>> '{key} {missing key}'.format_map(SafeSub({'key': 'value'}))
'value {missing key}'
"""
def __missing__(self, key):
return '{' + key + '}'
class KeyReplacer(dict):
"""Use with str.format_map to strip curly braces from missing keys.
'{key} {missing key}'.format_map(KeyReplacer({'key': 'value'}))
'value missing key'
"""
def __missing__(self, key):
return key
def fmt(s, **kwargs):
"""Format the string using local variables.
Additional variables may be specified via kwargs, which override
any local variable names.
Missing names do not raise exceptions.
>>> x = 2; fmt('{x} {y}')
'2 {y}'
"""
# Frame hack: get locals() from one level up
keys = SafeSub(sys._getframe(1).f_locals)
keys.update(kwargs)
return s.format_map(keys)
@magic
class show:
"""
>>> x = '''ayy
lmao'''
>>> show.x
x = 'ayy\nlmao'
"""
def __getattr__(self, name):
try:
value = sys._getframe(1).f_locals[name]
except KeyError as exc:
# inspect.unwrap relies on hasattr, which literally just
# calls getattr and checks for AttributeError.
# doctest uses inspect.unwrap, otherwise this would not
# merit fixing here.
raise AttributeError(exc)
print('{} = {!r}'.format(name, value))
def __call__(self, *exclude):
f_locals = sys._getframe(1).f_locals
for name in sorted(f_locals):
if name not in exclude:
print('{} = {!r}'.format(name, f_locals[name]))
def vars_repr(obj, var_names=None, var_filter=None):
"""Return a repr string from the specified instance attributes.
If no names are specified, uses all vars.
>>> class Thing:
... not_a_var = 'vars are instance attrs; this is a class attr'
... def __init__(self, **kwargs):
... self.__dict__.update(kwargs)
... __repr__ = vars_repr
>>> Thing(a=1, b=2)
Thing(a=1, b=2)
>>> vars_repr(Thing(a=1, b=2), ['a', 'bogus'])
'Thing(a=1)'
"""
repr_vars = subdict(vars(obj), keys=var_names, item_filter=var_filter)
return callstr(obj, **repr_vars)
def attr_repr(obj, attr_names=None):
"""Return a repr string from the specified attributes.
If no attributes are specified, uses all "public" attributes
(names that don't begin with an underscore).
>>> class Thing:
... a = 1
... def __init__(self):
... self.b = 2
... @property
... def c(self):
... return 3
... def method(self):
... return 4
... def __repr__(self):
... return attr_repr(self, ['a', 'b', 'c'])
>>> Thing()
Thing(a=1, b=2, c=3)
"""
if attr_names is None:
attr_names = [name for name in dir(obj) if not name.startswith('_')]
attrs = {name: getattr(obj, name) for name in attr_names}
return callstr(obj, **attrs)
def argstr(*args, **kwargs):
"""Return a string representation of the given signature.
Lists kwargs in sorted order.
>>> argstr(1, 2, 3)
'(1, 2, 3)'
>>> argstr()
'()'
>>> argstr(a=1)
'(a=1)'
>>> argstr(1, 2, c=3)
'(1, 2, c=3)'
>>> argstr(a=1, c=3, b=2)
'(a=1, b=2, c=3)'
"""
if not args and not kwargs:
return '()'
args_str = ', '.join(repr(arg) for arg in args)
kwargs_str = ', '.join('{}={!r}'.format(k, v)
for k, v in sorted(kwargs.items()))
if not args:
return f'({kwargs_str})'
if not kwargs:
return f'({args_str})'
return f'({args_str}, {kwargs_str})'
def callstr(*args, **kwargs):
"""Return a string representation of a call to the given object.
>>> def ayy(): pass
>>> callstr(ayy, 'lm', a='o')
"ayy('lm', a='o')"
>>> class ayy: pass
>>> callstr(ayy, 'lm', a='o')
"ayy('lm', a='o')"
>>> class ayy: pass
>>> callstr(ayy(), 'lm', a='o')
"ayy('lm', a='o')"
"""
first, *rest = args
try:
name = first.__name__
except AttributeError:
name = first.__class__.__name__
return name + argstr(*rest, **kwargs)
def count(items, singular, plural=None, zero=None, *, suffix='s'):
"""Return a properly pluralized string representing the number of items.
>>> one, two, zero = 'a', 'aa', ''
>>> count(one, 'apple')
'1 apple'
>>> count(two, 'apple')
'2 apples'
>>> count(zero, 'apple')
'0 apples'
>>> count(one, 'octopus')
'1 octopus'
>>> count(two, 'octopus', suffix='es')
'2 octopuses'
>>> count(two, 'octopus', 'octopi')
'2 octopi'
>>> count(zero, 'octopus', 'octopi', zero='octopi (whew!)')
'0 octopi (whew!)'
"""
if plural is None:
plural = singular + suffix
if zero is None:
zero = plural
n = len(items)
if n == 0:
word = zero
elif n == 1:
word = singular
else:
word = plural
return '{} {}'.format(n, word)
def pl(singular, plural, zero=None, placeholder='#'):
"""Return a function that returns an appropriate phrase for a given number.
Args:
singular: appropriate phrase for N=1.
plural: appropriate phrase for N>1.
zero: appropriate phrase for N=0. If None, uses plural.
placeholder: string which will be replaced with the count when
the selected phrase is returned. (Placeholder may simply be
omitted from the phrases if not needed.)
Returns:
a function which returns the correct phrase for the count it is
given.
>>> phrase = pl('# failure', '# failures')
>>> phrase(1)
'1 failure'
>>> phrase(5)
'5 failures'
>>> phrase(0)
'0 failures'
>>> phrase('two')
'two failures'
>>> phrase(1, word='one')
'one failure'
>>> phrase = pl('# failure', '# failures', zero='All passed!')
>>> phrase(1)
'1 failure'
>>> phrase(5)
'5 failures'
>>> phrase(0)
'All passed!'
>>> n = 10; phrase(n, word=n if n < 5 else 'Too many')
'Too many failures'
>>> phrase = pl('one', 'more than one', zero='no')
>>> phrase(1)
'one'
>>> phrase(5)
'more than one'
>>> phrase(0)
'no'
>>> phrase = pl(
... "You're the best!",
... "Y'all are the best!",
... zero="Nobody here :(")
>>> phrase(1)
"You're the best!"
>>> phrase(3)
"Y'all are the best!"
>>> phrase(0)
'Nobody here :('
>>> phrase = pl('# apple was bad', '# apples were bad')
>>> phrase(1)
'1 apple was bad'
>>> phrase(1.5)
'1.5 apples were bad'
>>> phrase(3)
'3 apples were bad'
>>> phrase(0)
'0 apples were bad'
>>> n = 1; phrase(n, word=['no', 'a single', 'multiple'][n])
'a single apple was bad'
>>> n = 0; phrase(n, word=['no', 'a single', 'multiple'][n])
'no apples were bad'
"""
if zero is None:
zero = plural
def pluralizable(count, *, word=None):
"""Return an appropriate phrase based on the given count.
Substitutes the placeholder with the count, or word if it is
given (e.g., "one million", "too many").
"""
if word is None:
word = str(count)
if count == 0:
phrase = zero
elif count == 1:
phrase = singular
else:
phrase = plural
return phrase.replace(placeholder, word)
return pluralizable
if __name__ == '__main__':
import doctest
doctest.testmod()