動的にインポートされたモジュールから追加機能をsingledispatch関数に登録しようとしています。動的にインポートされたモジュールでsingledispatch関数を登録する
main.py
from importlib import import_module
from functools import singledispatch
@singledispatch
def handle(a):
return 'default'
def import_something():
other_module = import_module('dynimp')
handle_result = handle(1)
assert handle_result == 'int', f'Error: {handle_result}'
if __name__ == '__main__':
import_something()
dynimp.py
from main import handle
@handle.register(int)
def handle_int(a):
return 'int'
import_something
でアサーションが失敗し、私は'default'
、ない'int'
を取得します。
もう少し調べました。関数オブジェクトは、dynimp
にインポートされると何とかコピーされます。 other_module = import_module('dynimp')
の後にブレークポイントを設定した場合、other_module.handle != handle
とother_module.registry
はhandle.registry
のようにhandle_int
と表示されます。その後、
def do_register(handle_fn):
handle_fn.register(int, handle_int)
とimport_something
機能でother_module.do_register(handle)
を追加します。
機能するソリューションは、dynimp.py
でregister
機能を持っており、それをhandle
を渡すことです。
私の質問は次のとおりです。装飾された関数をインポートするとどうなりますか?なぜこれは機能しませんか?