|
| 1 | +"""Base Packager class.""" |
| 2 | + |
| 3 | +import inspect |
| 4 | +from pathlib import Path |
| 5 | +import sys |
| 6 | +import textwrap |
| 7 | + |
| 8 | +from skbase.base import BaseObject |
| 9 | +from skbase.utils.dependencies import _check_estimator_deps |
| 10 | + |
| 11 | + |
| 12 | +class _BasePkg(BaseObject): |
| 13 | + |
| 14 | + _tags = { |
| 15 | + "python_dependencies": None, |
| 16 | + "python_version": None, |
| 17 | + # package register and manifest |
| 18 | + "pkg_id": None, # object id contained, "__multiple" if multiple |
| 19 | + "pkg_obj": "reference", # or "code" |
| 20 | + "pkg_obj_type": None, # openml API type |
| 21 | + "pkg_compression": "zlib", # compression |
| 22 | + } |
| 23 | + |
| 24 | + def __init__(self): |
| 25 | + super().__init__() |
| 26 | + |
| 27 | + def materialize(self): |
| 28 | + try: |
| 29 | + _check_estimator_deps(obj=self) |
| 30 | + except ModuleNotFoundError as e: |
| 31 | + # prettier message, so the reference is to the pkg_id |
| 32 | + # currently, we cannot simply pass the object name to skbase |
| 33 | + # in the error message, so this is a hack |
| 34 | + # todo: fix this in scikit-base |
| 35 | + msg = str(e) |
| 36 | + if len(msg) > 11: |
| 37 | + msg = msg[11:] |
| 38 | + raise ModuleNotFoundError(msg) from e |
| 39 | + |
| 40 | + return self._materialize() |
| 41 | + |
| 42 | + def _materialize(self): |
| 43 | + raise RuntimeError("abstract method") |
| 44 | + |
| 45 | + def serialize(self): |
| 46 | + cls_str = class_to_source(type(self)) |
| 47 | + compress_method = self.get_tag("pkg_compression") |
| 48 | + if compress_method in [None, "None"]: |
| 49 | + return cls_str |
| 50 | + |
| 51 | + cls_str = cls_str.encode("utf-8") |
| 52 | + exec(f"import {compress_method}") |
| 53 | + compressed_str = eval(f"{compress_method}.compress(cls_str)") |
| 54 | + |
| 55 | + return compressed_str |
| 56 | + |
| 57 | + |
| 58 | +def _has_source(obj) -> bool: |
| 59 | + """ |
| 60 | + Return True if inspect.getsource(obj) should succeed. |
| 61 | + """ |
| 62 | + module_name = getattr(obj, "__module__", None) |
| 63 | + if not module_name or module_name not in sys.modules: |
| 64 | + return False |
| 65 | + |
| 66 | + module = sys.modules[module_name] |
| 67 | + file = getattr(module, "__file__", None) |
| 68 | + if not file: |
| 69 | + return False |
| 70 | + |
| 71 | + return Path(file).suffix == ".py" |
| 72 | + |
| 73 | + |
| 74 | +def class_to_source(cls) -> str: |
| 75 | + """Return full source definition of python class as string. |
| 76 | +
|
| 77 | + Parameters |
| 78 | + ---------- |
| 79 | + cls : class to serialize |
| 80 | +
|
| 81 | + Returns |
| 82 | + ------- |
| 83 | + str : complete definition of cls, as str. |
| 84 | + Imports are not contained or serialized. |
| 85 | + """"" |
| 86 | + |
| 87 | + # Fast path: class has retrievable source |
| 88 | + if _has_source(cls): |
| 89 | + source = inspect.getsource(cls) |
| 90 | + return textwrap.dedent(source) |
| 91 | + |
| 92 | + # Fallback for dynamically created classes |
| 93 | + lines = [] |
| 94 | + |
| 95 | + bases = [base.__name__ for base in cls.__bases__ if base is not object] |
| 96 | + base_str = f"({', '.join(bases)})" if bases else "" |
| 97 | + lines.append(f"class {cls.__name__}{base_str}:") |
| 98 | + |
| 99 | + body_added = False |
| 100 | + |
| 101 | + for name, value in cls.__dict__.items(): |
| 102 | + if name.startswith("__") and name.endswith("__"): |
| 103 | + continue |
| 104 | + |
| 105 | + if inspect.isfunction(value): |
| 106 | + if _has_source(value): |
| 107 | + method_src = inspect.getsource(value) |
| 108 | + method_src = textwrap.indent(textwrap.dedent(method_src), " ") |
| 109 | + lines.append(method_src) |
| 110 | + else: |
| 111 | + lines.append(f" def {name}(self): ...") |
| 112 | + body_added = True |
| 113 | + else: |
| 114 | + lines.append(f" {name} = {repr(value)}") |
| 115 | + body_added = True |
| 116 | + |
| 117 | + if not body_added: |
| 118 | + lines.append(" pass") |
| 119 | + |
| 120 | + return "\n".join(lines) |
0 commit comments