Completed
Branch master (ea8775)
by Fabio
02:39 queued 01:33
created

benedict.utils.keypath_util.list_keys()   B

Complexity

Conditions 6

Size

Total Lines 14
Code Lines 11

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 6
eloc 11
nop 2
dl 0
loc 14
rs 8.6666
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
3
from benedict.utils import dict_util
4
5
from six import string_types
6
7
8
def check_keys(d, separator):
9
    """
10
    Check if dict keys contain keypath separator.
11
    """
12
    if not isinstance(d, dict) or not separator:
13
        return
14
15
    def check_key(parent, key, value):
16
        if key and isinstance(key, string_types) and separator in key:
17
            raise ValueError(
18
                'keys should not contain keypath separator '
19
                '\'{}\', found: \'{}\'.'.format(separator, key))
20
    dict_util.traverse(d, check_key)
21
22
23
def list_keys(keypath, separator):
24
    """
25
    List keys splitting a keypath using the given separator.
26
    """
27
    if isinstance(keypath, string_types):
28
        if separator and separator in keypath:
29
            return list(keypath.split(separator))
30
        return [keypath]
31
    elif isinstance(keypath, (list, tuple, )):
32
        keys = []
33
        for key in keypath:
34
            keys += list_keys(key, separator)
35
        return keys
36
    return [keypath]
37