|
| 1 | +import importlib |
| 2 | +from types import ModuleType |
| 3 | +from typing import Optional, Tuple |
| 4 | + |
| 5 | + |
| 6 | +class FromClause: |
| 7 | + """from句のモジュールを保持し、from句関連の処理を担当するクラス |
| 8 | +
|
| 9 | + from xxx import yyy の xxx 部分(from句)のモジュールを保持し、 |
| 10 | + サブモジュールのインポートやモジュール/アトリビュート判定を行います。 |
| 11 | +
|
| 12 | + Attributes: |
| 13 | + _module: from句で指定されたモジュール |
| 14 | + _base_module: 基準となるモジュール(import文が記述されているモジュール) |
| 15 | + """ |
| 16 | + |
| 17 | + def __init__(self, module: ModuleType, base_module: ModuleType) -> None: |
| 18 | + self._module = module |
| 19 | + self._base_module = base_module |
| 20 | + |
| 21 | + @property |
| 22 | + def module(self) -> ModuleType: |
| 23 | + """from句のモジュールを取得""" |
| 24 | + return self._module |
| 25 | + |
| 26 | + @classmethod |
| 27 | + def resolve(cls, base_module: ModuleType, level: int, module_name: Optional[str]) -> Optional['FromClause']: |
| 28 | + """from句のモジュールを解決してFromClauseインスタンスを生成 |
| 29 | +
|
| 30 | + Args: |
| 31 | + base_module: 基準となるモジュール(import文が記述されているモジュール) |
| 32 | + level: 相対インポートのレベル (0=絶対, 1=".", 2="..", ...) |
| 33 | + module_name: モジュール名(from . import yyy の場合はNone) |
| 34 | +
|
| 35 | + Returns: |
| 36 | + FromClauseインスタンス、失敗時はNone |
| 37 | +
|
| 38 | + 例: |
| 39 | + - from math import sin |
| 40 | + → level=0, module_name='math' → mathモジュール |
| 41 | + - from . import helper |
| 42 | + → level=1, module_name=None → 親パッケージ |
| 43 | + - from .utils import func |
| 44 | + → level=1, module_name='utils' → utilsモジュール |
| 45 | + - from ..config import VALUE |
| 46 | + → level=2, module_name='config' → configモジュール |
| 47 | + """ |
| 48 | + if level > 0 and module_name is None: |
| 49 | + # from . import yyy パターン |
| 50 | + module = cls._import_relative_parent_package(base_module, level) |
| 51 | + else: |
| 52 | + # from xxx import yyy パターン |
| 53 | + module = cls._import_from_clause(base_module, level, module_name) |
| 54 | + |
| 55 | + if module is None: |
| 56 | + return None |
| 57 | + |
| 58 | + return cls(module, base_module) |
| 59 | + |
| 60 | + def try_import_as_module(self, name: str, is_relative_dot_only: bool) -> Tuple[bool, Optional[ModuleType]]: |
| 61 | + """nameをモジュールとしてインポート試行(モジュール/アトリビュート判定のため) |
| 62 | +
|
| 63 | + モジュール/アトリビュートの分類判定に使用。 |
| 64 | + 成功すればモジュール、失敗すればアトリビュート(関数/クラス/変数)と判断される。 |
| 65 | +
|
| 66 | + Args: |
| 67 | + name: インポートする名前 |
| 68 | + is_relative_dot_only: from . import yyy パターンかどうか |
| 69 | +
|
| 70 | + Returns: |
| 71 | + (is_module, module): is_moduleがTrueならモジュール、Falseならアトリビュート |
| 72 | + """ |
| 73 | + # どちらのパターンでもサブモジュールとしてインポートを試行 |
| 74 | + module_candidate = self._try_import_submodule(name) |
| 75 | + |
| 76 | + is_module = module_candidate is not None and module_candidate is not self._base_module |
| 77 | + return (is_module, module_candidate if is_module else None) |
| 78 | + |
| 79 | + def _try_import_submodule(self, name: str) -> Optional[ModuleType]: |
| 80 | + """from句のモジュールから指定された名前をサブモジュールとしてインポートを試行 |
| 81 | +
|
| 82 | + Args: |
| 83 | + name: インポートする名前 |
| 84 | +
|
| 85 | + Returns: |
| 86 | + インポートされたサブモジュール、失敗時はNone |
| 87 | + """ |
| 88 | + try: |
| 89 | + full_name = f'{self._module.__name__}.{name}' |
| 90 | + return importlib.import_module(full_name) |
| 91 | + except (ModuleNotFoundError, ImportError): |
| 92 | + return None |
| 93 | + |
| 94 | + @staticmethod |
| 95 | + def _import_from_clause(base_module: ModuleType, level: int, module_name: Optional[str]) -> Optional[ModuleType]: |
| 96 | + """from句で指定されたモジュールをインポート |
| 97 | +
|
| 98 | + Args: |
| 99 | + base_module: 基準となるモジュール |
| 100 | + level: 相対インポートのレベル (0=絶対, 1=".", 2="..", ...) |
| 101 | + module_name: モジュール名 |
| 102 | + """ |
| 103 | + try: |
| 104 | + if level > 0: |
| 105 | + # 相対インポート(from .xxx import yyy)の場合 |
| 106 | + return FromClause._import_from_clause_relative(base_module, level, module_name) |
| 107 | + else: |
| 108 | + # 絶対インポート(from xxx import yyy)の場合 |
| 109 | + return importlib.import_module(module_name) |
| 110 | + except (ModuleNotFoundError, ImportError): |
| 111 | + return None |
| 112 | + |
| 113 | + @staticmethod |
| 114 | + def _import_from_clause_relative(base_module: ModuleType, level: int, module_name: str) -> Optional[ModuleType]: |
| 115 | + """from句の相対インポートでモジュールをインポートする |
| 116 | +
|
| 117 | + Args: |
| 118 | + base_module: 基準となるモジュール |
| 119 | + level: 相対インポートのレベル (1 = ".", 2 = "..", ...) |
| 120 | + module_name: インポートするモジュール名 |
| 121 | +
|
| 122 | + Returns: |
| 123 | + インポートされたモジュール、失敗時はNone |
| 124 | + """ |
| 125 | + try: |
| 126 | + # パッケージ(__path__を持つ)の場合、level - 1 を使用 |
| 127 | + if hasattr(base_module, '__path__'): |
| 128 | + actual_level = level - 1 |
| 129 | + else: |
| 130 | + actual_level = level |
| 131 | + |
| 132 | + if actual_level == 0: |
| 133 | + base_name = base_module.__name__ |
| 134 | + else: |
| 135 | + base_name = base_module.__name__.rsplit('.', actual_level)[0] |
| 136 | + |
| 137 | + target_name = f'{base_name}.{module_name}' |
| 138 | + return importlib.import_module(target_name) |
| 139 | + except (ModuleNotFoundError, ImportError): |
| 140 | + return None |
| 141 | + |
| 142 | + @staticmethod |
| 143 | + def _import_relative_parent_package(base_module: ModuleType, level: int) -> Optional[ModuleType]: |
| 144 | + """相対インポートの親パッケージをインポートする |
| 145 | +
|
| 146 | + Args: |
| 147 | + base_module: 基準となるモジュール |
| 148 | + level: 相対インポートのレベル (1 = ".", 2 = "..", ...) |
| 149 | +
|
| 150 | + Returns: |
| 151 | + インポートされた親パッケージ、失敗時はNone |
| 152 | + """ |
| 153 | + try: |
| 154 | + # パッケージ(__path__を持つ)の場合、level - 1 を使用 |
| 155 | + if hasattr(base_module, '__path__'): |
| 156 | + actual_level = level - 1 |
| 157 | + else: |
| 158 | + actual_level = level |
| 159 | + |
| 160 | + if actual_level == 0: |
| 161 | + # 自分自身のパッケージ |
| 162 | + return base_module |
| 163 | + else: |
| 164 | + parent_name = base_module.__name__.rsplit('.', actual_level)[0] |
| 165 | + return importlib.import_module(parent_name) |
| 166 | + except (ModuleNotFoundError, ImportError, ValueError): |
| 167 | + return None |
0 commit comments