File: modobj.py

package info (click to toggle)
python-setoptconf 0.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 252 kB
  • sloc: python: 1,427; sh: 7; makefile: 5
file content (59 lines) | stat: -rw-r--r-- 1,771 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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
import types

from ..config import Configuration
from .base import Source


__all__ = (
    'ModuleSource',
    'ObjectSource',
)


class ModuleSource(Source):
    def __init__(self, target):
        super(ModuleSource, self).__init__()

        if isinstance(target, types.ModuleType):
            self.target = target
        elif isinstance(target, str):
            self.target = __import__(target, globals(), locals(), [], -1)
        else:
            raise TypeError(
                'target must be a Module or a String naming a Module'
            )

    def get_config(self, settings, manager=None, parent=None):
        for setting in settings:
            if hasattr(self.target, setting.name):
                setting.value = getattr(self.target, setting.name)

        return Configuration(settings=settings, parent=parent)


class ObjectSource(Source):
    def __init__(self, target):
        super(ObjectSource, self).__init__()

        if isinstance(target, (type, object)):
            self.target = target
        elif isinstance(target, str):
            parts = target.rsplit('.', 2)
            if len(parts) == 2:
                mod = parts[0]
                fromlist = [parts[1]]
            else:
                mod = parts[0]
                fromlist = []
            self.target = __import__(mod, globals(), locals(), fromlist, -1)
        else:
            raise TypeError(
                'target must be an Object or a String naming an Object'
            )

    def get_config(self, settings, manager=None, parent=None):
        for setting in settings:
            if hasattr(self.target, setting.name):
                setting.value = getattr(self.target, setting.name)

        return Configuration(settings=settings, parent=parent)