-
Notifications
You must be signed in to change notification settings - Fork 15
Expand file tree
/
Copy pathappend.py
More file actions
61 lines (42 loc) · 1.4 KB
/
append.py
File metadata and controls
61 lines (42 loc) · 1.4 KB
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
60
61
# =========================================
# DEPS
# --------------------------------------
import sys
from os import path
CURRENT_PATH = path.abspath(path.dirname(__file__))
ROOT_PATH = path.abspath(path.join(CURRENT_PATH, ".."))
try:
try:
sys.path.remove(CURRENT_PATH)
except:
pass
sys.path.index(ROOT_PATH)
except ValueError:
sys.path.insert(0, ROOT_PATH)
import rootpath
# =========================================
# FUNCTIONS
# --------------------------------------
def append(current_path=None, pattern=None):
"""
Automatically adds current file's package root to Python load path (i.e. `sys.path`) unless already added.
This makes it possible to always ensure module imports behave same no matter how the file is loaded.
Examples:
rootpath.append()
rootpath.append(__file__)
rootpath.append('./src')
"""
project_root_path = rootpath.detect(current_path, pattern)
if project_root_path is None:
return False, project_root_path
try:
if current_path is not None and project_root_path != current_path:
try:
sys.path.remove(current_path)
except:
pass
sys.path.index(project_root_path)
return False, project_root_path
except ValueError:
sys.path.append(project_root_path)
return True, project_root_path