File size: 1,558 Bytes
43c5292
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import collections.abc as abc
import copy
import pydoc
from typing import Any


class DictConfig(dict):

    def __getattr__(self, item):
        try:
            return self[item]
        except KeyError:
            raise AttributeError(f"'AttrDict' object has no attribute '{item}'")

    def __setattr__(self, key, value):
        self[key] = value

    def __delattr__(self, item):
        try:
            del self[item]
        except KeyError:
            raise AttributeError(f"'DictConfig' object has no attribute '{item}'")


def locate(name: str) -> Any:
    """
    Locate and return an object using a string like {x.__module__}.{x.__qualname__}.

    Args:
        name:Dotted path to the object

    Returns:
        The located object

    Raises:
        ImportError if the object cannot be found
    """
    return pydoc.locate(name)



class LazyObject:

    def __init__(self, target, **kwargs):
        self._target = target
        self._kwargs = kwargs

    def instantiate(self, **kwargs):
        new_kwargs = copy.deepcopy(self._kwargs)
        new_kwargs.update(kwargs)
        return self._target(**new_kwargs)


class LazyCall:

    def __init__(self, target):
        if not callable(target):
            raise ValueError(f"`target` of LazyCall must be a callable, got {target}")
        self._target = target

    def __call__(self, **kwargs):
        return LazyObject(self._target, **kwargs)


def instantiate(config: LazyObject, **kwargs):
    if config is None:
        return None
    return config.instantiate(**kwargs)