cihai / cihai
1
# -*- coding: utf8 - *-
2 2
"""
3
Utility and helper methods for cihai.
4
"""
5 2
from __future__ import absolute_import, print_function, unicode_literals
6

7 2
import sys
8

9 2
from . import exc
10 2
from ._compat import collections_abc, reraise
11

12

13 2
def merge_dict(base, additional):
14
    """
15
    Combine two dictionary-like objects.
16

17
    Notes
18
    -----
19
    Code from https://github.com/pypa/warehouse
20
    Copyright 2013 Donald Stufft
21

22
    Licensed under the Apache License, Version 2.0 (the "License");
23
    you may not use this file except in compliance with the License.
24
    You may obtain a copy of the License at
25

26
    http://www.apache.org/licenses/LICENSE-2.0
27

28
    Unless required by applicable law or agreed to in writing, software
29
    distributed under the License is distributed on an "AS IS" BASIS,
30
    WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
31
    See the License for the specific language governing permissions and
32
    limitations under the License.
33
    """
34 2
    if base is None:
35 2
        return additional
36

37 2
    if additional is None:
38 0
        return base
39

40 2
    if not (
41
        isinstance(base, collections_abc.Mapping)
42
        and isinstance(additional, collections_abc.Mapping)
43
    ):
44 0
        return additional
45

46 2
    merged = base
47 2
    for key, value in additional.items():
48 2
        if isinstance(value, collections_abc.Mapping):
49 2
            merged[key] = merge_dict(merged.get(key), value)
50
        else:
51 2
            merged[key] = value
52

53 2
    return merged
54

55

56 2
def supports_wide():
57
    """Return affirmative if python interpreter supports wide characters.
58

59
    Returns
60
    -------
61
    bool :
62
        True if python supports wide character sets
63
    """
64 0
    return sys.maxunicode > 0xFFFF
65

66

67 2
def import_string(import_name, silent=False):  # NOQA: C901
68
    """
69
    Imports an object based on a string.
70

71
    This is useful if you want to use import paths as endpoints or
72
    something similar.  An import path can  be specified either in dotted
73
    notation (``xml.sax.saxutils.escape``) or with a colon as object
74
    delimiter (``xml.sax.saxutils:escape``).
75

76
    If `silent` is True the return value will be `None` if the import fails.
77

78
    Parameters
79
    ----------
80
    import_name : string
81
        the dotted name for the object to import.
82
    silent : bool
83
        if set to `True` import errors are ignored and `None` is returned instead.
84

85
    Returns
86
    -------
87
    imported object
88

89
    Raises
90
    ------
91
    cihai.exc.ImportStringError (ImportError, cihai.exc.CihaiException)
92

93
    Notes
94
    -----
95
    This is from werkzeug.utils c769200 on May 23, LICENSE BSD.
96
    https://github.com/pallets/werkzeug
97

98
    Changes:
99
    - Exception raised is cihai.exc.ImportStringError
100
    - Add NOQA C901 to avoid complexity lint
101
    - Format with black
102
    """
103
    # force the import name to automatically convert to strings
104
    # __import__ is not able to handle unicode strings in the fromlist
105
    # if the module is a package
106 2
    import_name = str(import_name).replace(':', '.')
107 2
    try:
108 2
        try:
109 2
            __import__(import_name)
110 2
        except ImportError:
111 2
            if '.' not in import_name:
112 2
                raise
113
        else:
114 2
            return sys.modules[import_name]
115

116 2
        module_name, obj_name = import_name.rsplit('.', 1)
117 2
        try:
118 2
            module = __import__(module_name, None, None, [obj_name])
119 0
        except ImportError:
120
            # support importing modules not yet set up by the parent module
121
            # (or package for that matter)
122 0
            module = import_string(module_name)
123

124 2
        try:
125 2
            return getattr(module, obj_name)
126 2
        except AttributeError as e:
127 2
            raise ImportError(e)
128

129 2
    except ImportError as e:
130 2
        if not silent:
131 2
            reraise(
132
                exc.ImportStringError,
133
                exc.ImportStringError(import_name, e),
134
                sys.exc_info()[2],
135
            )

Read our documentation on viewing source code .

Loading