make_list()   C
last analyzed

Complexity

Conditions 7

Size

Total Lines 29

Duplication

Lines 0
Ratio 0 %

Importance

Changes 2
Bugs 0 Features 0
Metric Value
cc 7
c 2
b 0
f 0
dl 0
loc 29
rs 5.5
1
"""Standard filters."""
2
3
import re
4
5
import json
6
7
from string import ascii_lowercase
8
9
10
def camel2hyphen(string, **kwargs):
11
    """Convert a camelCaseString into a hyphenated one.
12
13
    Args:
14
        string (str): The string to format.
15
16
    Returns:
17
        string (str): The formatted string.
18
    """
19
    # CREDIT: http://stackoverflow.com/questions/1175208/
20
    # elegant-python-function-to-convert-camelcase-to-snake-case
21
    # (modified to use hyphen instead of underscores.)
22
    s1 = re.sub('(.)([A-Z][a-z]+)', r'\1-\2', string)
23
    return re.sub('([a-z0-9])([A-Z])', r'\1-\2', s1).lower()
24
25
26
def to_json(string, **kwargs):
27
    """Render json using native python module.
28
29
    Args:
30
        string (str): The string to format.
31
32
    Returns:
33
        string (str): The formatted string.
34
    """
35
    return json.dumps(string, **kwargs)
36
37
38
def css_selector(string, lowercase=True):
39
    """Convert a string to a css selector friendly format.
40
41
    Args:
42
        word (str): The string to format.
43
44
    Returns:
45
        word (str): The formatted word.
46
    """
47
    if not isinstance(string, str):
48
        return string
49
    string = re.sub(r'[^a-zA-Z0-9]', '-', string)
50
    string = re.sub(r'\-{2,}', '-', string)
51
    if not lowercase:
52
        return string
53
    return string.lower()
54
55
56
def title(word, capitalize=False):
57
    """Convert a string to a title format, where the words are capitalized.
58
59
    Args:
60
        word (str): The string to format.
61
62
    Returns:
63
        word (str): The formatted word.
64
    """
65
    def _capitalize(w):
66
        return '{0}{1}'.format(w[0].upper(), w[1:])
67
68
    if word is None:
69
        return ''
70
    words = word.split(' ')
71
    for i, word in enumerate(words):
72
        if i == 0 or capitalize:
73
            words[i] = _capitalize(word)
74
    return ' '.join(words)
75
76
77
def firstof(seq):
78
    """Return the first item that is truthy in a sequence.
79
80
    Equivalent to Djangos' firstof.
81
82
    Args:
83
        seq (list): A list of values.
84
85
    Returns:
86
        value (mixed): The output, depending on the truthiness of the input.
87
    """
88
    if not any(seq):
89
        return ''
90
    if all(seq):
91
        return seq[0]
92
    while seq:
93
        item = seq.pop(0)
94
        if item:
95
            return item
96
    return ''
97
98
99
def questionize_label(word):
100
    """Convert a word to a true/false style question format.
101
102
    If a user follows the convention of using `is_something`, or
103
    `has_something`, for a boolean value, the *property* text will
104
    automatically be converted into a more human-readable
105
    format, e.g. 'Something?' for is_ and Has Something? for has_.
106
107
    Args:
108
        word (str): The string to format.
109
110
    Returns:
111
        word (str): The formatted word.
112
    """
113
    if word is None:
114
        return ''
115
    if word.startswith('is_'):
116
        return '{0}?'.format(word[3:])
117
    elif word.startswith('has_'):
118
        return '{0}?'.format(word[4:])
119
    return word
120
121
122
def add(lst, arg):
123
    """Add an item to a list.
124
125
    Equivalent to Djangos' add.
126
127
    Args:
128
        lst (list): A list.
129
        arg (mixed): Any value to append to the list.
130
131
    Returns:
132
        list: The updated list.
133
    """
134
    lst.append(arg)
135
    return lst
136
137
138
def cut(val, removals):
139
    """Remove some value from a string.
140
141
    Similar to Djangos' cut, but accepts N arguments to remove, in turn.
142
143
    Args:
144
        val (str): A string.
145
        removals (list): Alist of values to remove in turn, from the value.
146
147
    Returns:
148
        str: The updated string.
149
    """
150
    def _cut(val, tocut):
151
        return val.replace(tocut, '')
152
    for r in removals:
153
        val = _cut(val, r)
154
    return val
155
156
157
def addslashes(val):
158
    """Add slashes before all single quotes in a given string.
159
160
    Equivalent to Djangos' addslashes.
161
162
    Args:
163
        val (str): A string.
164
165
    Returns:
166
        str: The updated string.
167
    """
168
    return val.replace("'", "\\'")
169
170
171
def default(val, default):
172
    """Default to a given value if another given value is falsy.
173
174
    Equivalent to Djangos' default.
175
176
    Args:
177
        val (mixed): A mixed value that is truthy or falsy.
178
        default (mixed): A default replacement value.
179
180
    Returns:
181
        mixed: The default given value, or the original value.
182
    """
183
    return default if not val else val
184
185
186
def default_if_none(val, default):
187
    """Default to a given value if another given value is None.
188
189
    Equivalent to Djangos' default_if_none.
190
191
    Args:
192
        val (mixed): A mixed value that may or may not be None.
193
        default (mixed): A default replacement value.
194
195
    Returns:
196
        mixed: The default given value, or the original value.
197
    """
198
    return default if val is None else val
199
200
201
def get_digit(val, index):
202
    """Return the digit of a value specified by an index.
203
204
    Equivalent to Djangos' get_digit.
205
206
    Args
207
        val (int): An integer.
208
        index (int): The index to check against.
209
210
    Returns:
211
        int: The original integer if index is invalid, otherwise the digit
212
        at the specified index.
213
    """
214
    digits = reversed(list(str(val)))
215
    for k, digit in enumerate(digits):
216
        if k + 1 == int(index):
217
            return int(digit)
218
    return val
219
220
221
def length_is(val, length):
222
    """Return True if the length of a given value matches a given length.
223
224
    Equivalent to Djangos' length_is.
225
226
    Args:
227
        val (mixed): A value to check the length of.
228
        length (int): The length to check.
229
230
    Returns:
231
        bool: The value of checking the length against length.
232
    """
233
    return len(val) == length
234
235
236
def is_url(val):
237
    """Return true if a value is a url string, otherwise false.
238
239
    Args:
240
        val (mixed): The value to check.
241
242
    Returns:
243
        bool: True if the value is an http string, False if not.
244
    """
245
    if isinstance(val, (str, unicode)):
246
        return val.startswith('http://') or val.startswith('https://')
247
    return False
248
249
250
def ljust(string, amt):
251
    """Left-align the value by the amount specified.
252
253
    Equivalent to Djangos' ljust.
254
255
    Args:
256
        string (str): The string to adjust.
257
        amt (int): The amount of space to adjust by.
258
259
    Returns:
260
        str: The padded string.
261
    """
262
    return string.ljust(amt)
263
264
265
def rjust(string, amt):
266
    """Right-align the value by the amount specified.
267
268
    Equivalent to Djangos' rjust.
269
270
    Args:
271
        string (str): The string to adjust.
272
        amt (int): The amount of space to adjust by.
273
274
    Returns:
275
        str: The padded string.
276
    """
277
    return string.rjust(amt)
278
279
280
def make_list(val, coerce_numbers=True):
281
    """Make a list from a given value.
282
283
    Roughly equivalent to Djangos' make_list, with some enhancements.
284
285
    Args:
286
        val (mixed): The value to convert.
287
        coerce_numbers (bool, optional): Whether or not string number
288
            should be coerced back to their original values.
289
290
    Returns:
291
        mixed: If dict is given, return d.items(). If list is given, return it.
292
            If integers given, return a list of digits.
293
            Otherwise, return a list of characters.
294
    """
295
    if isinstance(val, dict):
296
        return val.items()
297
    if isinstance(val, list):
298
        return val
299
    vals = list(str(val))
300
    if coerce_numbers and isinstance(val, str):
301
        lst = []
302
        for v in vals:
303
            try:
304
                lst.append(int(v))
305
            except ValueError:
306
                lst.append(v)
307
        return lst
308
    return vals
309
310
311
def phone2numeric(phoneword):
312
    """Convert a phoneword string into the translated number equivalent.
313
314
    Roughly equivalent to Djangos' phone2numeric.
315
316
    Args:
317
        phoneword (str): The phoneword string.
318
319
    Returns:
320
        str: The converted string digits.
321
    """
322
    two, three = ['a', 'b', 'c'], ['d', 'e', 'f']
323
    four, five = ['g', 'h', 'i'], ['j', 'k', 'l']
324
    six, seven = ['m', 'n', 'o'], ['p', 'q', 'r', 's']
325
    eight, nine = ['t', 'u', 'v'], ['w', 'x', 'y', 'z']
326
    newdigits = ''
327
    for digit in list(phoneword.lower()):
328
        if digit in two:
329
            newdigits += '2'
330
        elif digit in three:
331
            newdigits += '3'
332
        elif digit in four:
333
            newdigits += '4'
334
        elif digit in five:
335
            newdigits += '5'
336
        elif digit in six:
337
            newdigits += '6'
338
        elif digit in seven:
339
            newdigits += '7'
340
        elif digit in eight:
341
            newdigits += '8'
342
        elif digit in nine:
343
            newdigits += '9'
344
        else:
345
            newdigits += digit
346
    return newdigits
347
348
349
def pagetitle(string, remove_first=False, divider=' > '):
350
    """Convert a string of characters to page-title format.
351
352
    Args:
353
        string (str): The string to conert.
354
        remove_first (bool, optional): Remove the first instance of the
355
            delimiter of the newly formed title.
356
357
    Returns:
358
        str: The converted string.
359
    """
360
    _title = divider.join(string.split('/'))
361
    if remove_first:
362
        _title = _title.replace(divider, '', 1)
363
    return _title
364
365
366
def slugify(string):
367
    """Convert a string of characters to URL slug format.
368
369
    All characters replacing all characters with hyphens if invalid.
370
    Roughly equivalent to Djangos' slugify.
371
372
    Args:
373
        string (str): The string to slugify.
374
375
    Returns:
376
        str: The slugified string.
377
    """
378
    slug = ''
379
    accepted = ['-', '_'] + list(ascii_lowercase) + list('01234567890')
380
    end = len(string) - 1
381
    for k, char in enumerate(string.lower().strip()):
382
        if char not in accepted:
383
            # Forget about the last char if it would get replaced.
384
            if k < end:
385
                slug += '-'
386
        else:
387
            slug += char
388
    return slug
389
390
391
def greet(name, greeting='Hello'):
392
    """Add a greeting to a given name.
393
394
    Args:
395
        name (str): The name to greet.
396
        greeting (str, optional): An optional greeting override.
397
398
    Returns:
399
        str: The updated greeting string.
400
    """
401
    return '{0}, {1}!'.format(greeting, name)
402
403
404
def islist(item):
405
    """Check if an is item is a list - not just a sequence.
406
407
    Args:
408
        item (mixed): The item to check as a list.
409
410
    Returns:
411
        result (bool): True if the item is a list, False if not.
412
413
    """
414
    return isinstance(item, list)
415
416
417
def sql2dict(queryset):
418
    """Return a SQL alchemy style query result into a list of dicts.
419
420
    Args:
421
        queryset (object): The SQL alchemy result.
422
423
    Returns:
424
        result (list): The converted query set.
425
426
    """
427
    if queryset is None:
428
        return []
429
    return [record.__dict__ for record in queryset]
430