Reputation: 1
I am trying to instantiate a class at runtime (and I'm fairly new to Python). Seems the best way to do this is using getattr and import_module, but I'm stuck on the import_module bit. I have the following file structure:
src
|- doug_client
| |- __init__.py
| |- test_import.py
|
|- message_defn
| |- __init__.py
| |- error_rtn_msg.py
Within error_rtn_msg.py is a class called ErrorRtnMsg that I am trying to instantiate in the test_import.py module. Here is the code found in test_import.py:
import importlib
try:
msg_package = ".src.message_defn"
msg_module = "error_rtn_msg"
print(f"msg_module: {msg_module, msg_package}")
module = importlib.import_module(msg_module, msg_package)
print(f"module: {module}")
msg_class_type = getattr(module, "ErrorRtnMsg")
print(f"msg_class_type: {type(msg_class_type), msg_class_type}")
except Exception as e:
print(f"Exception creating msg class: {e}")
Here is the result:
msg_module: ('error_rtn_msg', '.src.message_defn')
Exception creating msg class: No module named 'error_rtn_msg'
I've tried defining the module in different ways ('..error_rnt_msg', '.src.message_defn.error_rtn_msg', but no luck. It seems I am just not specifying the relative paths correctly, but I'm at a loss at to how to do this. There are lots of pages discussing how to use the import_module function but haven't been able to find any that go into detail on how to specify the relative paths, or have concrete examples similar to my situation. Is there something I need to add to the init.py file?
Any help would be greatly appreciated. Thanks.
Upvotes: 0
Views: 17