I have a program that supports different communication protocols. The idea is, that the user chooses the protocol during startup and then the module supporting the respective protocol is imported.
The function below populates the protocol module with all functions and variables from the user-chosen protocol.
protocol.py:
def provide_protocol( name ):
for key, val in vars( __import__( name ) ).items():
if key.startswith( "__" ) and key.endswith( "__" ):
continue
vars()[key] = val
importlib.invalidate_caches()
name is provided by the user at program startup.
The issue is, that protocol.py is imported before this function is run and the program is not able to access the newly populated functions in this previously empty module.
Using invalidate_caches() from the importlib module does not change this.
I also tried, to remove protocol.py and create the whole module dynamically using importlib, but this also did not succeed:
__init__.py:
protocol = None
def provide_protocol( name ):
protocol = importlib.import_module( name )
importlib.invalidate_caches()
The problem seems to be identical, because if I import protocol, it seems to be None.
vars()[key] = valin a function just assigns to adictobject returned bylocals()which has no effect on anything.