abstract-utilities 0.2.2.492__py3-none-any.whl → 0.2.2.495__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (42) hide show
  1. abstract_utilities/__init__.py +0 -1
  2. abstract_utilities/file_utils/__init__.py +1 -2
  3. abstract_utilities/file_utils/imports/constants.py +6 -0
  4. abstract_utilities/file_utils/imports/imports.py +1 -1
  5. abstract_utilities/file_utils/imports/module_imports.py +1 -2
  6. abstract_utilities/file_utils/module_imports.py +12 -0
  7. abstract_utilities/file_utils/src/__init__.py +10 -0
  8. abstract_utilities/file_utils/src/file_filters.py +110 -0
  9. abstract_utilities/file_utils/src/file_reader.py +607 -0
  10. abstract_utilities/file_utils/src/file_utils.py +279 -0
  11. abstract_utilities/file_utils/src/filter_params.py +155 -0
  12. abstract_utilities/file_utils/src/find_collect.py +154 -0
  13. abstract_utilities/file_utils/src/initFunctionsGen.py +286 -0
  14. abstract_utilities/file_utils/src/map_utils.py +29 -0
  15. abstract_utilities/file_utils/src/pdf_utils.py +300 -0
  16. abstract_utilities/file_utils/src/type_checks.py +92 -0
  17. abstract_utilities/import_utils/__init__.py +2 -0
  18. abstract_utilities/import_utils/imports/__init__.py +4 -0
  19. abstract_utilities/import_utils/imports/constants.py +2 -0
  20. abstract_utilities/import_utils/imports/imports.py +4 -0
  21. abstract_utilities/import_utils/imports/module_imports.py +6 -0
  22. abstract_utilities/import_utils/imports/utils.py +30 -0
  23. abstract_utilities/import_utils/src/__init__.py +7 -0
  24. abstract_utilities/import_utils/src/clean_imports.py +122 -0
  25. abstract_utilities/import_utils/src/dot_utils.py +60 -0
  26. abstract_utilities/import_utils/src/extract_utils.py +42 -0
  27. abstract_utilities/import_utils/src/import_functions.py +46 -0
  28. abstract_utilities/import_utils/src/import_utils.py +299 -0
  29. abstract_utilities/import_utils/src/package_utils/__init__.py +139 -0
  30. abstract_utilities/import_utils/src/package_utils/context_utils.py +27 -0
  31. abstract_utilities/import_utils/src/package_utils/import_collectors.py +53 -0
  32. abstract_utilities/import_utils/src/package_utils/path_utils.py +28 -0
  33. abstract_utilities/import_utils/src/package_utils/safe_import.py +27 -0
  34. abstract_utilities/import_utils/src/package_utils.py +140 -0
  35. abstract_utilities/import_utils/src/sysroot_utils.py +57 -0
  36. abstract_utilities/path_utils.py +1 -12
  37. abstract_utilities/read_write_utils.py +66 -32
  38. {abstract_utilities-0.2.2.492.dist-info → abstract_utilities-0.2.2.495.dist-info}/METADATA +1 -1
  39. {abstract_utilities-0.2.2.492.dist-info → abstract_utilities-0.2.2.495.dist-info}/RECORD +42 -11
  40. {abstract_utilities-0.2.2.492.dist-info → abstract_utilities-0.2.2.495.dist-info}/top_level.txt +1 -0
  41. imports/__init__.py +36 -0
  42. {abstract_utilities-0.2.2.492.dist-info → abstract_utilities-0.2.2.495.dist-info}/WHEEL +0 -0
@@ -0,0 +1,2 @@
1
+ from .imports import *
2
+ from .src import *
@@ -0,0 +1,4 @@
1
+ from .imports import *
2
+ from .module_imports import *
3
+ from .constants import *
4
+ from .utils import *
@@ -0,0 +1,2 @@
1
+ IMPORT_TAG = 'import '
2
+ FROM_TAG = 'from '
@@ -0,0 +1,4 @@
1
+ from pathlib import Path
2
+ from typing import *
3
+ from types import MethodType
4
+ import os, sys, importlib, os, inspect, re, importlib.util, hashlib
@@ -0,0 +1,6 @@
1
+ from ...read_write_utils import read_from_file,write_to_file,get_text_or_read
2
+ from ...string_clean import eatAll,eatInner,eatElse,clean_line
3
+ from ...class_utils import get_caller_path
4
+ from ...list_utils import make_list
5
+ from ...path_utils import get_file_parts
6
+ from ...type_utils import is_number,make_list
@@ -0,0 +1,30 @@
1
+ import os
2
+ from .constants import *
3
+
4
+ def is_line_import(line):
5
+ if line and (line.startswith(FROM_TAG) or line.startswith(IMPORT_TAG)):
6
+ return True
7
+ return False
8
+ def is_line_group_import(line):
9
+ if line and (line.startswith(FROM_TAG) and IMPORT_TAG in line):
10
+ return True
11
+ return False
12
+
13
+ def is_from_line_group(line):
14
+ if line and line.startswith(FROM_TAG) and IMPORT_TAG in line and '(' in line:
15
+ import_spl = line.split(IMPORT_TAG)[-1]
16
+ import_spl_clean = clean_line(line)
17
+ if not import_spl_clean.endswith(')'):
18
+ return True
19
+ return False
20
+ def get_unique_name(string,list_obj):
21
+ if isinstance(list_obj,dict):
22
+ list_obj = list(list_obj.keys())
23
+ if string in list_obj:
24
+ nustring = f"{string}"
25
+ for i in range(len(list_obj)):
26
+ nustring = f"{string}_{i}"
27
+ if nustring not in list_obj:
28
+ break
29
+ string = nustring
30
+ return string
@@ -0,0 +1,7 @@
1
+ from .clean_imports import *
2
+ from .dot_utils import *
3
+ from .extract_utils import *
4
+ from .import_utils import *
5
+ from .import_functions import *
6
+ from .package_utils import *
7
+ from .sysroot_utils import *
@@ -0,0 +1,122 @@
1
+ from ..imports import *
2
+
3
+ from .package_utils import *
4
+
5
+ def get_text_or_read(text=None,file_path=None):
6
+ text = text or ''
7
+ imports_js = {}
8
+ if not text and file_path and os.path.isfile(file_path):
9
+ text=read_from_file(file_path)
10
+ return text
11
+ def is_line_import(line):
12
+ if line and (line.startswith(FROM_TAG) or line.startswith(IMPORT_TAG)):
13
+ return True
14
+ return False
15
+ def is_line_group_import(line):
16
+ if line and (line.startswith(FROM_TAG) and IMPORT_TAG in line):
17
+ return True
18
+ return False
19
+
20
+ def is_from_line_group(line):
21
+ if line and line.startswith(FROM_TAG) and IMPORT_TAG in line and '(' in line:
22
+ import_spl = line.split(IMPORT_TAG)[-1]
23
+ import_spl_clean = clean_line(line)
24
+ if not import_spl_clean.endswith(')'):
25
+ return True
26
+ return False
27
+
28
+ def get_all_imports(text=None,file_path=None,import_pkg_js=None):
29
+ if text and os.path.isfile(text):
30
+ file_path = text
31
+ text = read_from_file(text)
32
+ text = get_text_or_read(text=text,file_path=file_path)
33
+ lines = text.split('\n')
34
+ cleaned_import_list=[]
35
+ nu_lines = []
36
+ is_from_group = False
37
+ import_pkg_js = ensure_import_pkg_js(import_pkg_js,file_path=file_path)
38
+ for line in lines:
39
+ if line.startswith(IMPORT_TAG) and ' from ' not in line:
40
+ cleaned_import_list = get_cleaned_import_list(line)
41
+ import_pkg_js = add_imports_to_import_pkg_js("import",cleaned_import_list,import_pkg_js=import_pkg_js)
42
+ else:
43
+ if is_from_group:
44
+ import_pkg=is_from_group
45
+ line = clean_line(line)
46
+ if line.endswith(')'):
47
+ is_from_group=False
48
+ line=line[:-1]
49
+ imports_from_import_pkg = clean_imports(line)
50
+ import_pkg_js = add_imports_to_import_pkg_js(import_pkg,imports_from_import_pkg,import_pkg_js=import_pkg_js)
51
+
52
+ else:
53
+ import_pkg_js=update_import_pkg_js(line,import_pkg_js=import_pkg_js)
54
+ if is_from_line_group(line) and is_from_group == False:
55
+ is_from_group=get_import_pkg(line)
56
+ return import_pkg_js
57
+ def clean_all_imports(text=None,file_path=None,import_pkg_js=None):
58
+ if text and os.path.isfile(text):
59
+ file_path = text
60
+ text = read_from_file(text)
61
+ if not import_pkg_js:
62
+ import_pkg_js = get_all_imports(text=text,file_path=file_path)
63
+ import_pkg_js = ensure_import_pkg_js(import_pkg_js,file_path=file_path)
64
+ nu_lines = import_pkg_js["context"]["nulines"]
65
+ for pkg,values in import_pkg_js.items():
66
+ comments = []
67
+ if pkg not in ["context"]:
68
+ line = values.get('line')
69
+ imports = values.get('imports')
70
+ for i,imp in enumerate(imports):
71
+ if '#' in imp:
72
+ imp_spl = imp.split('#')
73
+ comments.append(imp_spl[-1])
74
+ imports[i] = clean_line(imp_spl[0])
75
+ imports = list(set(imports))
76
+ if '*' in imports:
77
+ imports="*"
78
+ else:
79
+ imports=','.join(imports)
80
+ if comments:
81
+ comments=','.join(comments)
82
+ imports+=f" #{comments}"
83
+ import_pkg_js[pkg]["imports"]=imports
84
+ nu_lines[line] += imports
85
+ import_pkg_js["context"]["nulines"]=nu_lines
86
+ return import_pkg_js
87
+ def get_dot_fro_line(line,dirname):
88
+ from_line = line.split(FROM_TAG)[-1]
89
+ dot_fro = ""
90
+ for char in from_line:
91
+ if char != '.':
92
+ line = f"from {dot_fro}{eatAll(from_line,'.')}"
93
+ break
94
+ dirname = os.path.dirname(dirname)
95
+ dirbase = os.path.basename(dirname)
96
+ dot_fro = f"{dirbase}.{dot_fro}"
97
+ return line
98
+ def get_dot_fro_lines(lines,file_path,all_imps):
99
+ for line in lines:
100
+ if line.startswith(FROM_TAG):
101
+ line = get_dot_fro_line(line,file_path)
102
+ if line in all_imps:
103
+ line = ""
104
+ if line:
105
+ all_imps.append(line)
106
+ return all_imps
107
+ def get_all_real_imps(text=None,file_path=None,all_imps=None):
108
+ if text and os.path.isfile(text):
109
+ file_path = text
110
+ text = read_from_file(text)
111
+ all_imps = all_imps or []
112
+ contents = get_text_or_read(text=text,file_path=file_path)
113
+ lines = contents.split('\n')
114
+ all_imps = get_dot_fro_lines(lines,file_path,all_imps)
115
+ return '\n'.join(all_imps)
116
+ def save_cleaned_imports(text=None,file_path=None,write=False,import_pkg_js=None):
117
+ import_pkg_js=get_all_imports(text=text,file_path=file_path,import_pkg_js=import_pkg_js)
118
+ import_pkg_js = clean_all_imports(text=text,file_path=file_path,import_pkg_js=import_pkg_js)
119
+ contents = '\n'.join(import_pkg_js["context"]["nulines"])
120
+ if file_path and write:
121
+ write_to_file(contents=contents,file_path=file_path)
122
+ return contents
@@ -0,0 +1,60 @@
1
+ from ..imports import *
2
+ def get_dot_range(filepath=None,list_obj=None):
3
+ imports = make_list(list_obj) or extract_imports(filepath)
4
+ highest=0
5
+ dots = [get_imp(fro) for fro in imports if fro]
6
+
7
+ if dots:
8
+ dots.sort()
9
+ highest = dots[0]
10
+ return highest
11
+ def dotted_from(file: Path, sysroot: Path) -> str:
12
+ """
13
+ Build dotted name from sysroot (directory *above* top package)
14
+ e.g. /repo/abstract_ide/consoles/launcherWindowTab/functions/core_utils.py
15
+ sysroot=/repo -> abstract_ide.consoles.launcherWindowTab.functions.core_utils
16
+ """
17
+ file = file.resolve()
18
+ stem = file.with_suffix("") # drop .py
19
+ return ".".join(stem.relative_to(sysroot).parts)
20
+ def to_dotted_name(file_path: Path, top_package: str) -> str:
21
+ """
22
+ Convert .../abstract_ide/consoles/launcherWindowTab/functions/core_utils.py
23
+ -> abstract_ide.consoles.launcherWindowTab.functions.core_utils
24
+ """
25
+ # find the index of the top_package in the path parts
26
+ parts = file_path.resolve().parts
27
+ i = None
28
+ if is_number(top_package):
29
+ i= int(top_package)
30
+ if i is None:
31
+ try:
32
+ i = parts.index(top_package)
33
+ except ValueError:
34
+ raise RuntimeError(f"Cannot locate package '{top_package}' in {file_path}")
35
+ rel_parts = parts[i:] # from top_package onward
36
+ if rel_parts[-1].endswith(".py"):
37
+ rel_parts = list(rel_parts)
38
+ rel_parts[-1] = rel_parts[-1][:-3] # strip .py
39
+ return ".".join(rel_parts)
40
+ def compute_dotted_and_sysroot(file_path: Path) -> Tuple[str, Path]:
41
+ """
42
+ If inside packages, build dotted name from the top package down.
43
+ sysroot will be the directory *above* the top package.
44
+ If not a package, we fall back to a repo-ish root guess (2 parents up).
45
+ """
46
+ file_path = file_path.resolve()
47
+ stem = file_path.with_suffix("") # drop .py
48
+
49
+ top_pkg_dir = find_top_package_dir(file_path)
50
+ if top_pkg_dir:
51
+ sysroot = top_pkg_dir.parent
52
+ dotted = ".".join(stem.relative_to(sysroot).parts)
53
+ return dotted, sysroot
54
+
55
+ # Fallback: not in a package tree — guess a root a couple levels up
56
+ sysroot = file_path.parents[2]
57
+ dotted = ".".join(stem.relative_to(sysroot).parts)
58
+ return dotted, sysroot
59
+
60
+
@@ -0,0 +1,42 @@
1
+ from ..imports import *
2
+ def get_imp(line):
3
+ lis = [li for li in line.split(' ') if li and li.startswith('.')]
4
+ if lis and len(lis) >0:
5
+ lis = lis[0]
6
+ lis = len(lis) - len(eatInner(lis,['.']))
7
+ return lis
8
+ return 0
9
+ def extract_imports(path,strings=None):
10
+ strings = make_list(strings or ['from','import'])
11
+ funcs = []
12
+ lines = read_from_file(path).splitlines()
13
+ return [line for line in lines if [string for string in strings if string and eatAll(line,[' ','\n','\t']) and eatAll(line,[' ','\n','\t']).startswith(string)]]
14
+
15
+ def extract_froms(path: str):
16
+ funcs = []
17
+ for line in read_from_file(path).splitlines():
18
+ m = re.match(r"^from\s+([A-Za-z_]\w*)\s*", line)
19
+ if m:
20
+ funcs.append(m.group(1))
21
+ return funcs
22
+ def extract_selfs(path: str):
23
+ funcs = []
24
+ for line in read_from_file(path).splitlines():
25
+ m = re.match(r"^def\s+([A-Za-z_]\w*)\s*\(self", line)
26
+ if m:
27
+ funcs.append(m.group(1))
28
+ return funcs
29
+ def extract_funcs(path: str):
30
+ funcs = []
31
+ for line in read_from_file(path).splitlines():
32
+ m = re.match(r"^def\s+([A-Za-z_]\w*)\s*\(", line)
33
+ if m:
34
+ funcs.append(m.group(1))
35
+ return funcs
36
+ def extract_class(path: str):
37
+ funcs = []
38
+ for line in read_from_file(path).splitlines():
39
+ m = re.match(r"^class\s+([A-Za-z_]\w*)\s*\(", line) or re.match(r"^class\s+([A-Za-z_]\w*)\s*\:", line)
40
+ if m:
41
+ funcs.append(m.group(1))
42
+ return funcs
@@ -0,0 +1,46 @@
1
+ # --- auto-package bootstrap (run-safe) ---------------------------------
2
+ from ..imports import *
3
+ from .dot_utils import get_dot_range
4
+ from .sysroot_utils import get_sysroot
5
+ def clean_imports(imports,commaClean=True):
6
+ chars=["*"]
7
+ if not commaClean:
8
+ chars.append(',')
9
+ if isinstance(imports,str):
10
+ imports = imports.split(',')
11
+ return [eatElse(imp,chars=chars) for imp in imports if imp]
12
+ def get_cleaned_import_list(line,commaClean=True):
13
+ cleaned_import_list=[]
14
+ if IMPORT_TAG in line:
15
+ imports = line.split(IMPORT_TAG)[1]
16
+ cleaned_import_list+=clean_imports(imports,commaClean=commaClean)
17
+ return cleaned_import_list
18
+ def get_module_from_import(imp,path=None):
19
+ path = path or os.getcwd()
20
+ i = get_dot_range(None,[imp])
21
+ imp = eatAll(imp,'.')
22
+ sysroot = get_sysroot(path,i)
23
+ return os.path.join(sysroot, imp)
24
+
25
+ def safe_import(name: str, *, package: str | None = None, member: str | None = None, file: str | None = None):
26
+ """
27
+ Wrapper over importlib.import_module that:
28
+ - if `name` is relative (starts with '.'), ensures `package` is set.
29
+ - if `package` is missing, derives it from `file` (defaults to __file__).
30
+ """
31
+ file = file or __file__
32
+ ensure_package_context(file)
33
+ if name.startswith(".") and not package:
34
+
35
+
36
+ pkg_name = get_module_from_import(name,path=None)
37
+ # also set __package__ if we are running as a script
38
+ if __name__ == "__main__" and (not globals().get("__package__")):
39
+ globals()["__package__"] = pkg_name
40
+ package = pkg_name
41
+
42
+ mod = importlib.import_module(name, package=package)
43
+ return getattr(mod, member) if member else mod
44
+
45
+
46
+
@@ -0,0 +1,299 @@
1
+ from ..imports import *
2
+ from .dot_utils import *
3
+ from .sysroot_utils import *
4
+ from .extract_utils import *
5
+ def find_top_package_dir(p: Path) -> Path | None:
6
+ p = p.resolve()
7
+ if p.is_file():
8
+ p = p.parent
9
+ top = None
10
+ while (p / "__init__.py").exists():
11
+ top = p
12
+ if p.parent == p:
13
+ break
14
+ p = p.parent
15
+ return top
16
+ def safe_import(name: str, package: str | None = None, member: str | None = None):
17
+ """
18
+ Wraps importlib.import_module but also resolves relative imports like '..logPaneTab'.
19
+ If `member` is given, returns that attribute from the module.
20
+ """
21
+ mod = importlib.import_module(name, package=package)
22
+ return getattr(mod, member) if member else mod
23
+ def unique_module_name(base: str, path: Path) -> str:
24
+ # Make a stable, unique name per file
25
+ digest = hashlib.md5(str(path.resolve()).encode()).hexdigest()[:8]
26
+ stem = path.stem.replace('-', '_')
27
+ return f"_dyn.{base}.{stem}_{digest}"
28
+
29
+ def import_from_path(module_name: str, file_path: Path):
30
+ spec = importlib.util.spec_from_file_location(module_name, str(file_path))
31
+ if spec is None or spec.loader is None:
32
+ raise ImportError(f"Could not load spec for {file_path}")
33
+ mod = importlib.util.module_from_spec(spec)
34
+ # Register before exec to satisfy intra-module relative imports (rare but safe)
35
+ sys.modules[module_name] = mod
36
+ spec.loader.exec_module(mod)
37
+ return mod
38
+ def get_imports(files: List[str],self=None) -> Dict[str, Dict[str, Any]]:
39
+ """
40
+ Discover package context from each file's relative-import requirements,
41
+ add the proper sysroot to sys.path once, and import by dotted name.
42
+ Returns: {modname: {"filepath", "sysroot", "module", "class", "funcs", "selfs"}}
43
+ """
44
+ results: Dict[str, Dict[str, Any]] = {}
45
+ seen_sysroots: set[str] = set()
46
+ files = make_list(files)
47
+ for file in files:
48
+ file_p = Path(file).resolve()
49
+
50
+ # 1) Use your logic to find a viable sysroot (top where dots won't exceed)
51
+ sysroot_guess = Path(get_dot_range_sysroot(str(file_p))).resolve()
52
+ # 2) Ensure we import with *package* context: we need the directory ABOVE
53
+ # the topmost package on sys.path, not the package dir itself.
54
+ top_pkg_dir = find_top_package_dir(sysroot_guess) or find_top_package_dir(file_p)
55
+ if not top_pkg_dir:
56
+ raise RuntimeError(f"No package context found for {file_p}; add __init__.py up the tree.")
57
+ sysroot = top_pkg_dir.parent
58
+
59
+ if str(sysroot) not in seen_sysroots:
60
+ ensure_on_path(sysroot)
61
+ seen_sysroots.add(str(sysroot))
62
+
63
+ # 3) Compute dotted name from sysroot and import
64
+ dotted = dotted_from(file_p, sysroot)
65
+ try:
66
+ mod = importlib.import_module(dotted)
67
+ except Exception as e:
68
+ # Helpful hint if user ran file directly (no package context)
69
+ if "__package__" in dir() and not __package__:
70
+ raise RuntimeError(
71
+ f"Import failed for {dotted}. If you ran this file directly, "
72
+ f"bootstrap package context or run via `python -m ...`."
73
+ ) from e
74
+ raise
75
+
76
+ # 4) Collect symbols (you can keep your regex readers if you prefer)
77
+ classes = extract_class(str(file_p))
78
+ funcs = extract_funcs(str(file_p))
79
+ selfs = extract_selfs(str(file_p))
80
+
81
+ # stable result key (avoid collisions)
82
+ key = get_unique_name(get_file_parts(str(file_p))['filename'], results)
83
+
84
+ results[key] = {
85
+ "filepath": str(file_p),
86
+ "sysroot": str(sysroot),
87
+ "module": mod,
88
+ "class": classes,
89
+ "funcs": funcs,
90
+ "selfs": selfs,
91
+ }
92
+
93
+ return results
94
+ def inject_symbols_from_module(
95
+ mod,
96
+ into: dict,
97
+ *,
98
+ expose_functions: bool = True,
99
+ expose_classes: bool = True,
100
+ expose_methods: bool = False,
101
+ self: object | None = None, # <---- NEW
102
+ ctor_overrides: Mapping[str, Tuple[tuple, dict]] | None = None,
103
+ name_prefix: str = "",
104
+ name_filter: Iterable[str] | None = None,
105
+ overwrite: bool = False
106
+ ) -> Dict[str, Any]:
107
+ """
108
+ Inject functions/classes from `mod` into `into` (usually globals()).
109
+ If expose_methods=True and a `self` object is passed, bind instance methods
110
+ directly onto `self` instead of globals().
111
+ """
112
+ exported: Dict[str, Any] = {}
113
+ ctor_overrides = ctor_overrides or {}
114
+
115
+ def allowed(name: str) -> bool:
116
+ return name_filter is None or name in name_filter
117
+
118
+ # 1) functions
119
+ if expose_functions:
120
+ for name, obj in vars(mod).items():
121
+ input(name)
122
+ if not allowed(name):
123
+ continue
124
+ if inspect.isfunction(obj) and obj.__module__ == mod.__name__:
125
+ out_name = f"{name_prefix}{name}"
126
+ if overwrite or out_name not in into:
127
+ into[out_name] = obj
128
+ exported[out_name] = obj
129
+
130
+ # 2) classes (+ optional bound methods)
131
+ if expose_classes or expose_methods:
132
+ for cls_name, cls in vars(mod).items():
133
+ if not allowed(cls_name):
134
+ continue
135
+ if inspect.isclass(cls) and cls.__module__ == mod.__name__:
136
+ if expose_classes:
137
+ out_name = f"{name_prefix}{cls_name}"
138
+ if overwrite or out_name not in into:
139
+ into[out_name] = cls
140
+ exported[out_name] = cls
141
+
142
+ if expose_methods and self is not None:
143
+ # instantiate class
144
+ args, kwargs = ctor_overrides.get(cls_name, ((), {}))
145
+ try:
146
+ inst = cls(*args, **kwargs)
147
+ except Exception:
148
+ continue
149
+
150
+ for meth_name, meth_obj in vars(cls).items():
151
+ if meth_name.startswith("__"):
152
+ continue
153
+ if inspect.isfunction(meth_obj) or inspect.ismethoddescriptor(meth_obj):
154
+ try:
155
+ bound = getattr(inst, meth_name)
156
+ except Exception:
157
+ continue
158
+ if callable(bound):
159
+ # attach directly to the `self` you passed in
160
+ if not hasattr(self, meth_name) or overwrite:
161
+ setattr(self, meth_name, bound)
162
+ exported[f"{cls_name}.{meth_name}"] = bound
163
+
164
+ return exported
165
+ def inject_from_imports_map(
166
+ imports_map: Dict[str, Dict[str, Any]],
167
+ *,
168
+ into: Optional[dict] = None, # where to put free funcs/classes (defaults to this module's globals)
169
+ attach_self: Optional[object] = None, # bind names listed in "selfs" onto this object
170
+ prefix_modules: bool = False, # add "<module>__" prefix to avoid collisions
171
+ overwrite: bool = False, # allow overwriting existing names
172
+ self:any=None
173
+ ) -> Dict[str, Any]:
174
+ """
175
+ Emulates: from functions import * (plus: bind 'self' methods)
176
+ Returns dict of injected_name -> object (including methods bound to attach_self).
177
+ """
178
+ ns = into if into is not None else globals()
179
+ exported: Dict[str, Any] = {}
180
+
181
+ for mod_key, info in imports_map.items():
182
+ mod = info.get("module")
183
+ if mod is None:
184
+ continue
185
+
186
+ func_names: List[str] = info.get("funcs", [])
187
+ self_names: List[str] = info.get("selfs", [])
188
+ class_names: List[str] = info.get("class", [])
189
+
190
+ # 1) bind the "selfs" directly onto self
191
+ if self is not None:
192
+ for name in self_names:
193
+ func = getattr(mod, name, None)
194
+ if not callable(func):
195
+ continue
196
+ # sanity: ensure first param is literally named 'self'
197
+ try:
198
+ params = list(inspect.signature(func).parameters.values())
199
+ if not params or params[0].name != "self":
200
+ continue
201
+ except Exception:
202
+ continue
203
+
204
+ bound = MethodType(func, self)
205
+ if overwrite or not hasattr(self, name):
206
+ setattr(self, name, bound)
207
+ exported[f"{mod_key}.self.{name}"] = bound
208
+
209
+ # 2) Inject free functions (exclude the ones we just bound to self to avoid dupes)
210
+ for name in func_names:
211
+ if name in self_names:
212
+ continue
213
+ obj = getattr(mod, name, None)
214
+ if inspect.isfunction(obj) and obj.__module__ == mod.__name__:
215
+ out_name = f"{mod_key}__{name}" if prefix_modules else name
216
+ if overwrite or out_name not in ns:
217
+ ns[out_name] = obj
218
+ exported[out_name] = obj
219
+
220
+ # 3) Inject classes
221
+ for name in class_names:
222
+ cls = getattr(mod, name, None)
223
+ if inspect.isclass(cls) and cls.__module__ == mod.__name__:
224
+ out_name = f"{mod_key}__{name}" if prefix_modules else name
225
+ if overwrite or out_name not in ns:
226
+ ns[out_name] = cls
227
+ exported[out_name] = cls
228
+
229
+ # optional: control wildcard export from THIS module
230
+ ns["__all__"] = sorted(set(list(ns.get("__all__", [])) + list(exported.keys())))
231
+ return exported
232
+ def ifFunctionsInFiles(root: str | None = None, *, expose_methods: bool = True, self=None) -> Dict[str, Any]:
233
+ here = Path(__file__).resolve().parent
234
+ base = Path(root).resolve() if root else here
235
+ candidates = [base / "functions", base / "functions.py"]
236
+ files: List[str] = []
237
+ for item in candidates:
238
+ if item.exists():
239
+ if item.is_dir():
240
+ files = [str(p) for p in item.rglob("*.py") if p.name != "__init__.py"]
241
+ else:
242
+ files = [str(item)]
243
+ break
244
+
245
+ exported_all: Dict[str, Any] = {}
246
+ imports_map = get_imports(files)
247
+
248
+ exported = inject_from_imports_map(
249
+ imports_map,
250
+ self=self
251
+ )
252
+
253
+ return exported
254
+ def attach_self_functions(
255
+ imports_map: Dict[str, Dict[str, Any]],
256
+ self_obj: object,
257
+ *,
258
+ overwrite: bool = False,
259
+ only: Optional[List[str]] = None, # whitelist of method names to attach
260
+ prefix_modules: bool = False # attach as core_utils__on_run_code instead of on_run_code
261
+ ) -> Dict[str, Any]:
262
+ """
263
+ For each module in imports_map, bind names listed in 'selfs' (top-level defs whose
264
+ first param is 'self') directly onto `self_obj`.
265
+
266
+ Returns {attached_name: bound_method}.
267
+ """
268
+ attached: Dict[str, Any] = {}
269
+
270
+ for mod_key, info in imports_map.items():
271
+ mod = info.get("module")
272
+ if not mod:
273
+ continue
274
+
275
+ self_names: List[str] = info.get("selfs", [])
276
+ for name in self_names:
277
+ if only is not None and name not in only:
278
+ continue
279
+
280
+ func = getattr(mod, name, None)
281
+ if not callable(func):
282
+ continue
283
+
284
+ # sanity check: first param literally named 'self'
285
+ try:
286
+ params = list(inspect.signature(func).parameters.values())
287
+ if not params or params[0].name != "self":
288
+ continue
289
+ except Exception:
290
+ continue
291
+
292
+ bound = MethodType(func, self_obj)
293
+ out_name = f"{mod_key}__{name}" if prefix_modules else name
294
+
295
+ if overwrite or not hasattr(self_obj, out_name):
296
+ setattr(self_obj, out_name, bound)
297
+ attached[out_name] = bound
298
+
299
+ return attached