Completed
Push — develop ( ce1198...1cbae8 )
by Kale
9s
created

AttrDict.__init__()   A

Complexity

Conditions 1

Size

Total Lines 3

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 1
dl 0
loc 3
rs 10
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
"""Common collection classes."""
3
from __future__ import print_function, division, absolute_import
4
from functools import reduce
5
6
from .compat import text_type
7
8
9
# http://stackoverflow.com/a/14620633/2127762
10
class AttrDict(dict):
11
    """Sub-classes dict, and further allows attribute-like access to dictionary items.
12
13
    Examples:
14
        >>> d = AttrDict({'a': 1})
15
        >>> d.a, d['a'], d.get('a')
16
        (1, 1, 1)
17
        >>> d.b = 2
18
        >>> d.b, d['b']
19
        (2, 2)
20
    """
21
    def __init__(self, *args, **kwargs):
22
        super(AttrDict, self).__init__(*args, **kwargs)
23
        self.__dict__ = self
24
25
26
class frozendict(dict):
27
28
    def __key(self):
29
        return tuple((k, self[k]) for k in sorted(self))
30
31
    def __hash__(self):
32
        return hash(self.__key())
33
34
    def __eq__(self, other):
35
        return self.__key() == other.__key()
36
37
38
def first(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
39
    """Give the first value that satisfies the key test.
40
41
    Args:
42
        seq (iterable):
43
        key (callable): test for each element of iterable
44
        default: returned when all elements fail test
45
        apply (callable): applied to element before return
46
47
    Returns: first element in seq that passes key, mutated with optional apply
48
49
    Examples:
50
        >>> first([0, False, None, [], (), 42])
51
        42
52
        >>> first([0, False, None, [], ()]) is None
53
        True
54
        >>> first([0, False, None, [], ()], default='ohai')
55
        'ohai'
56
        >>> import re
57
        >>> m = first(re.match(regex, 'abc') for regex in ['b.*', 'a(.*)'])
58
        >>> m.group(1)
59
        'bc'
60
61
        The optional `key` argument specifies a one-argument predicate function
62
        like that used for `filter()`.  The `key` argument, if supplied, must be
63
        in keyword form.  For example:
64
        >>> first([1, 1, 3, 4, 5], key=lambda x: x % 2 == 0)
65
        4
66
67
    """
68
    return next((apply(x) for x in seq if key(x)), default)
69
70
71
def firstitem(map, key=lambda k, v: bool(k), default=None, apply=lambda k, v: (k, v)):
72
    return next((apply(k, v) for k, v in map if key(k, v)), default)
73
74
75
def last(seq, key=lambda x: bool(x), default=None, apply=lambda x: x):
76
    return next((apply(x) for x in reversed(seq) if key(x)), default)
77
78
79
def call_each(seq):
80
    """Calls each element of sequence to invoke the side effect.
81
82
    Args:
83
        seq:
84
85
    Returns: None
86
87
    """
88
    try:
89
        reduce(lambda _, y: y(), seq)
90
    except TypeError as e:
91
        if text_type(e) != "reduce() of empty sequence with no initial value":
92
            raise
93