source: orange/Orange/OrangeCanvas/utils/__init__.py @ 11623:26ecc3a85f9c

Revision 11623:26ecc3a85f9c, 1.5 KB checked in by Ales Erjavec <ales.erjavec@…>, 9 months ago (diff)

Refactored utility functions.

Line 
1from .qtcompat import sip_getapi, toPyObject
2
3
4def dotted_getattr(obj, name):
5    """
6    `getattr` like function accepting a dotted name for attribute lookup.
7    """
8    return reduce(getattr, name.split("."), obj)
9
10
11def qualified_name(obj):
12    """
13    Return a qualified name for `obj` (type or function).
14    """
15    if obj.__name__ == "__builtin__":
16        return obj.__name__
17    else:
18        return "%s.%s" % (obj.__module__, obj.__name__)
19
20
21def name_lookup(qualified_name):
22    """
23    Return the object referenced by a qualified name (dotted name).
24    """
25    if "." not in qualified_name:
26        qualified_name = "__builtin__." + qualified_name
27
28    module_name, class_name = qualified_name.rsplit(".", 1)
29    module = __import__(module_name, fromlist=[class_name])
30    return getattr(module, class_name)
31
32
33def asmodule(module):
34    """
35    Return the :class:`module` instance named by `module`.
36
37    If `module` is already a module instance and not a string, return
38    it unchanged.
39
40    """
41    if isinstance(module, str):
42        module = __import__(module, fromlist=[])
43    return module
44
45
46def check_type(obj, type_or_tuple):
47    if not isinstance(obj, type_or_tuple):
48        raise TypeError("Expected %r. Got %r" % (type_or_tuple, type(obj)))
49
50
51def check_subclass(cls, class_or_tuple):
52    if not issubclass(cls, class_or_tuple):
53        raise TypeError("Expected %r. Got %r" % (class_or_tuple, type(cls)))
54
55
56def check_arg(pred, value):
57    if not pred:
58        raise ValueError(value)
Note: See TracBrowser for help on using the repository browser.