LoginSignup
1
0

More than 1 year has passed since last update.

[Python]Classモジュールの中でimport_moduleを利用して処理タイプ毎に動的にモジュールを読み込み実行する

Last updated at Posted at 2023-01-21

やりたいこと

Classモジュールの中に処理タイプ毎のモジュールを用意しておき動的に読み込み実行する

Code

動作確認環境: Python 3.7.10

test.py
test_class/
  ├ __init__.py
  └ func/
    ├ hoge.py
    └ fuga.py
test_class/__init__.py
from importlib import import_module

class test_class():
  def __init__(self, func_type):
    self.func = import_module(f".func.{func_type}", "test_class")

  def exec(self):
    self.func.main('test message'h)

Classの中ではimport_moduleを利用して動的にモジュールを読み込む
この時import_moduleはtest_classモジュールからの相対PATHで記載する

test_class/func/hoge.py
def main(message):
  print(f"hoge {message}")
test_class/func/fuga.py
def main(message):
  print(f"fuga {message}")

それぞれの処理であるhoge.pyとfuga.pyでは、同じ関数を用意しておくこと

test.py
from test_class import test_class

hoge = test_class('hoge')
hoge.exec()

fuga = test_class('fuga')
fuga.exec()

→これのアウトプットは

hoge test message
fuga test message

実際に利用する際は外部からの入力で読み込むモジュールを変更する

背景

EventBridgeからINVOKEされるLambdaで、渡されるeventタイプ毎に処理を定義したかった。
eventタイプは将来的に増える可能性があったため、eventタイプを追加する際に以下のポイントを見たす構成として本構成を採用した。

  • 既存のコードを極力編集せずに処理を追加可能
  • 万が一追加されたeventタイプのコードがエラーであったとしても、既存のeventタイプに対する処理に影響が出ない

eventタイプごとに、Lambdaを用意するという方法も検討したが、eventタイプが増えるに従いlambda関数が増殖するのを避けたかった。

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0