Completed
Push — master ( 0eea43...df739c )
by George
02:01
created

add_current_dir_to_syspath()   A

Complexity

Conditions 4

Size

Total Lines 18

Duplication

Lines 0
Ratio 0 %

Importance

Changes 0
Metric Value
cc 4
dl 0
loc 18
rs 9.2
c 0
b 0
f 0
1
# -*- coding: utf-8 -*-
2
# vi:si:et:sw=4:sts=4:ts=4
3
4
from functools import wraps
5
import importlib
6
import os
7
import sys
8
9
10
def add_current_dir_to_syspath(f):
11
12
    @wraps(f)
13
    def wrapper(*args, **kwargs):
14
        current = os.getcwd()
15
        changed = False
16
        if current not in sys.path:
17
            sys.path.append(current)
18
            changed = True
19
20
        try:
21
            return f(*args, **kwargs)
22
        finally:
23
            # restore sys.path
24
            if changed is True:
25
                sys.path.remove(current)
26
27
    return wrapper
28
29
30
@add_current_dir_to_syspath
31
def import_callable(full_name):
32
    package, *name = full_name.rsplit('.', 1)
33
    try:
34
        module = importlib.import_module(package)
35
    except ValueError as exc:
36
        raise ImportError('Error trying to import {!r}'.format(full_name)) from exc
37
38
    if name:
39
        handler = getattr(module, name[0])
40
    else:
41
        handler = module
42
43
    if not callable(handler):
44
        raise ImportError('{!r} should be callable'.format(full_name))
45
46
    return handler
47