File: module_loading.py

package info (click to toggle)
python-graphene 3.4.3-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,124 kB
  • sloc: python: 8,935; makefile: 212; sh: 18
file content (45 lines) | stat: -rw-r--r-- 1,587 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
from functools import partial
from importlib import import_module


def import_string(dotted_path, dotted_attributes=None):
    """
    Import a dotted module path and return the attribute/class designated by the
    last name in the path. When a dotted attribute path is also provided, the
    dotted attribute path would be applied to the attribute/class retrieved from
    the first step, and return the corresponding value designated by the
    attribute path. Raise ImportError if the import failed.
    """
    try:
        module_path, class_name = dotted_path.rsplit(".", 1)
    except ValueError:
        raise ImportError("%s doesn't look like a module path" % dotted_path)

    module = import_module(module_path)

    try:
        result = getattr(module, class_name)
    except AttributeError:
        raise ImportError(
            'Module "%s" does not define a "%s" attribute/class'
            % (module_path, class_name)
        )

    if not dotted_attributes:
        return result
    attributes = dotted_attributes.split(".")
    traveled_attributes = []
    try:
        for attribute in attributes:
            traveled_attributes.append(attribute)
            result = getattr(result, attribute)
        return result
    except AttributeError:
        raise ImportError(
            'Module "%s" does not define a "%s" attribute inside attribute/class "%s"'
            % (module_path, ".".join(traveled_attributes), class_name)
        )


def lazy_import(dotted_path, dotted_attributes=None):
    return partial(import_string, dotted_path, dotted_attributes)