File: utils.py

package info (click to toggle)
python-igraph 0.11.8%2Bds-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 3,480 kB
  • sloc: ansic: 24,545; python: 21,699; sh: 107; makefile: 35; sed: 2
file content (54 lines) | stat: -rw-r--r-- 1,209 bytes parent folder | download | duplicates (3)
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
"""Utility functions for unit testing."""

import os
import platform
import tempfile

from contextlib import contextmanager
from textwrap import dedent

__all__ = ("temporary_file",)


@contextmanager
def overridden_configuration(key, value):
    from igraph import config

    old_value = config[key]
    config[key] = value
    try:
        yield
    finally:
        config[key] = old_value


@contextmanager
def temporary_file(content=None, mode=None, binary=False):
    tmpf, tmpfname = tempfile.mkstemp()
    os.close(tmpf)

    if mode is None:
        if content is None:
            mode = "rb"
        else:
            mode = "wb"

    tmpf = open(tmpfname, mode)
    if content is not None:
        if hasattr(content, "encode") and not binary:
            tmpf.write(dedent(content).encode("utf8"))
        else:
            tmpf.write(content)

    tmpf.close()
    yield tmpfname
    try:
        os.unlink(tmpfname)
    except Exception:
        # ignore exceptions; it happens sometimes on Windows in the CI environment
        # that it cannot remove the temporary file because another process (?) is
        # using it...
        pass


is_pypy = platform.python_implementation() == "PyPy"