File: _util.py

package info (click to toggle)
python-eliot 1.16.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 964 kB
  • sloc: python: 8,641; makefile: 151
file content (56 lines) | stat: -rw-r--r-- 1,375 bytes parent folder | download
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
"""
Utilities that don't go anywhere else.
"""

from types import ModuleType


def safeunicode(o):
    """
    Like C{str()}, but catches and swallows any raised exceptions.

    @param o: An object of some sort.

    @return: C{str(o)}, or an error message if that failed.
    @rtype: C{str}
    """
    try:
        return str(o)
    except:
        # Not much we can do about this...
        return "eliot: unknown, str() raised exception"


def saferepr(o):
    """
    Like C{str(repr())}, but catches and swallows any raised exceptions.

    @param o: An object of some sort.

    @return: C{str(repr(o))}, or an error message if that failed.
    @rtype: C{str}
    """
    try:
        return str(repr(o))
    except:
        # Not much we can do about this...
        return "eliot: unknown, str() raised exception"


def load_module(name, original_module):
    """
    Load a copy of a module, distinct from what you'd get if you imported
    it directly.

    @param str name: The name of the new module.
    @param original_module: The original module we're recreating.

    @return: A new, distinct module.
    """
    import importlib.util

    module = ModuleType(name)
    spec = importlib.util.find_spec(original_module.__name__)
    source = spec.loader.get_code(original_module.__name__)
    exec(source, module.__dict__, module.__dict__)
    return module