94
|
1 |
import types
|
|
2 |
|
|
3 |
FLATTEN_TYPES = (tuple, list, types.GeneratorType)
|
|
4 |
|
|
5 |
def flatten (*items):
|
|
6 |
"""
|
|
7 |
Flatten common containers/iterables
|
|
8 |
|
|
9 |
>>> list(flatten())
|
|
10 |
[]
|
|
11 |
>>> list(flatten(1, 2, 3))
|
|
12 |
[1, 2, 3]
|
|
13 |
>>> list(flatten((1, 2, 3)))
|
|
14 |
[1, 2, 3]
|
|
15 |
>>> list(flatten((1, 2), 3))
|
|
16 |
[1, 2, 3]
|
|
17 |
>>> list(flatten((1, ), [2], (i for i in [3])))
|
|
18 |
[1, 2, 3]
|
|
19 |
"""
|
|
20 |
|
|
21 |
for item in items:
|
|
22 |
if item is None:
|
|
23 |
continue
|
|
24 |
|
|
25 |
elif isinstance(item, FLATTEN_TYPES):
|
|
26 |
for node in item:
|
|
27 |
yield from flatten(node)
|
|
28 |
|
|
29 |
else:
|
|
30 |
yield item
|
|
31 |
|
|
32 |
def merge (*dicts, **kwargs):
|
|
33 |
"""
|
|
34 |
Merge dicts.
|
|
35 |
|
|
36 |
>>> merge(foo=1, bar=2)
|
|
37 |
{'foo': 1, 'bar': 2}
|
|
38 |
>>> merge(dict(foo=1), bar=2)
|
|
39 |
{'foo': 1, 'bar': 2}
|
|
40 |
>>> merge(dict(foo=1), bar=2, foo=3)
|
|
41 |
{'foo': 3, 'bar': 2}
|
|
42 |
>>> merge(dict(foo=1), dict(bar=2), foo=3)
|
|
43 |
{'foo': 3, 'bar': 2}
|
|
44 |
>>> merge(dict(bar=2), dict(foo=1), foo=3)
|
|
45 |
{'foo': 3, 'bar': 2}
|
|
46 |
>>> merge(dict(foo=1), dict(foo=2), foo=3)
|
|
47 |
{'foo': 3}
|
|
48 |
"""
|
|
49 |
|
|
50 |
# later duplicate keys override
|
|
51 |
return {k: v for d in (dicts + (kwargs, )) for k, v in d.items()}
|