-
Notifications
You must be signed in to change notification settings - Fork 230
Description
Checklist
- There are no similar issues or pull requests for this yet.
Problem
I do a lot of my work in an IDE like Visual Studio Code and really appreciate good type hinting that allows for autocomplete/suggestion features. Currently, the DictList class in COBRApy doesn't have very good type hinting. For example, in the following code, I would like VSCode to automaticaly know that reaction is a cobra.Reaction object:
model = cobra.io.read_sbml_model("path/to/model.sbml")
for reaction in model.reactions:
... # hinted type for reaction is Any but should be cobra.Reaction
# Or using .get_by_id
reaction = model.reactions.get_by_id("rxn_id") # hinted type is cobra.Object but should be cobra.ReactionCurrently, I have to explicitly state that reaction is a cobra.Reaction object in order to get the expected autocomplete/suggestion features like this:
model = cobra.io.read_sbml_model("path/to/model.sbml")
for reaction in model.reactions:
reaction: cobra.Reaction
... # hinted type for reaction is cobra.Reaction
# Or using .get_by_id
reaction: cobra.Reaction = model.reactions.get_by_id("rxn_id")Solution
I believe the appropriate type hinting can be accomplished using a TypeVar from the typing module. I believe something along these lines should do the trick (and should support python versions 3.5+):
from typing import TypeVar, List, Iterable
from .object import Object
_TObject = TypeVar("_TObject", Object)
class DictList(List[_TObject]):
def __init__(self, *args: Iterable[_TObject]):
...
# example type hinting for get_by_id method
def get_by_id(self, id: Union[_TObject, str]) -> _TObject:
...You would then have to add some type hinting in the cobra.Model class to specify the type for each DictList instance:
# within __init__ method for cobra.core.model.Model
self.reactions: DictList[Reaction] = DictList()
self.metabolites: DictList[Metabolite] = DictList()
# etc.Alternatives
No response
Anything else?
Not sure if this is something that other people would want added or if there is a reason to not add it that I am missing. I would be happy to put together a PR for it.