2 years ago
#292726

Stewart
How to detect method signatures of imported python modules
I have a python app which can load and run extensions. It looks like this:
import importlib, sys
sys.path.append('.')
module = importlib.import_module( 'extension' )
Extension = getattr(module, 'Extension')
instance = Extension()
instance.FunctionCall(arg1='foo')
The users can create their own loadable extension by implementing a class I defined. In this case, it is in extension.py:
class Extension:
def FunctionCall(self, arg1):
print(arg1)
This works great for now, but I would like to extend my interface to pass another argument into Extension.FunctionCall
instance.FunctionCall(arg1='foo', arg2='bar')
How can I do this while maintaining reverse compatibility with the existing interface?
Here's what happens to existing users if I make the change:
$ python3 loader.py
Traceback (most recent call last):
File "loader.py", line 9, in <module>
instance.FunctionCall(arg1='foo', arg2='bar')
TypeError: FunctionCall() got an unexpected keyword argument 'arg2'
One option is to catch the TypeError, but is this the best solution? It looks like it could get unmaintainable with several iterations of interfaces.
try:
instance.FunctionCall(arg1='foo', arg2='bar')
except TypeError:
instance.FunctionCall(arg1='foo')
Another option is to define the "interface version" as a property of the extension and then use that in a case statement, but it would be nicer to simply detect what is supported instead of pushing overhead to the users.
if hasattr(Extension, 'Standard') and callable(getattr(Extension, 'Standard')):
standard=instance.Standard()
else:
standard=0
if standard == 0:
instance.FunctionCall(arg1='foo')
elif standard == 1:
instance.FunctionCall(arg1='foo', arg2='bar')
python
python-importlib
0 Answers
Your Answer