I am writing a "plugin" for an existing python package and wondering how I would properly type-hint something like this.
Scenario
A python object from a framework I am working with has a plugins
attribute that is designed to be extended by user-created plugins. For instance: (very simplified)
# External module that I have no control over
from typing import Any
class BaseClassPluginsCollection:
...
class BaseClass:
def __init__(self):
self.attr_a = 'a'
self.plugins = BaseClassPluginsCollection()
def add_plugin(self, plugin: Any, plugin_name: str):
setattr(self.plugins, plugin_name, plugin)
So the plugins
attribute is basically an empty object which users (like myself) will add new plugin objects to. So in my case, I might do something like this:
class MyCustomPlugin:
def __init__(self):
self.my_attr_a = "my attribute"
my_plugin = MyCustomPlugin()
base_object = BaseClass()
base_object.add_plugin(my_plugin, "my_plugin")
In practice, this all works fine and I can add and then use the plugin during program execution without issue. However, I would like to properly type-hint this so that my IDE knows about the plugin. Is such a thing even possible?
Currently (using VS Code) I get the red squiggly line when I try and reference my plugin, even though it does work fine during execution.
For instance, if I try and use the base_object
created above, I get an error from the static type checker:
print(f"{base_object.plugins.my_plugin.my_attr_a=}")
What would be the appropriate way to handle this type of scenario? Is there a method for type-hinting something of this sort when its being added during execution using setattr()
? Should I be doing some sort if aliasing before trying to access my_plugin
?