opencobra / cobrapy

COBRApy is a package for constraint-based modeling of metabolic networks.
http://opencobra.github.io/cobrapy/
GNU General Public License v2.0
467 stars 218 forks source link

cobra.core.formula.Formula gives maximum recursion depth exceeded error #1291

Closed axelvonkamp closed 2 years ago

axelvonkamp commented 2 years ago

Problem description

I want to use the Formula class to get molecular weights for formulas. I try to use it like this:

>>> from cobra.core.formula import Formula
>>> Formula("H")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/scratch/vonkamp/gwdg_owncloud/github/cobrapy/src/cobra/core/object.py", line 124, in __repr__
    return f"<{self.__class__.__name__} {self.id} at {id(self):#x}>"
  File "/scratch/vonkamp/gwdg_owncloud/github/cobrapy/src/cobra/core/object.py", line 134, in __str__
    return str(self.id)
  File "/scratch/vonkamp/gwdg_owncloud/github/cobrapy/src/cobra/core/object.py", line 134, in __str__
    return str(self.id)
  File "/scratch/vonkamp/gwdg_owncloud/github/cobrapy/src/cobra/core/object.py", line 134, in __str__
    return str(self.id)
  [Previous line repeated 329 more times]
RecursionError: maximum recursion depth exceeded

A simple workaround is for the class Formula to be standalone, i.e. not derive it from cobra.core.object.Object:

-class Formula(Object):
+class Formula:
     """Describe a chemical formula.

     Parameters
@@ -30,7 +30,6 @@ class Formula(Object):
         formula: str, optional
             An string that will be parsed as a formula.
         """
-        super().__init__(self, formula, **kwargs)

I'm not sure what the intention is do derive Formula from cobra.core.object.Object but without this it works as expected:

>>> from cobra.core.formula import Formula
>>> Formula("H")
<cobra.core.formula.Formula object at 0x7f391cd6f650>
>>> Formula("H").weight
1.00794

python -c "import cobra;cobra.show_versions()" -->

System Information

OS Linux OS-release 5.15.0-41-generic Python 3.7.10

Package Versions

appdirs 1.4.4 cobra 0.25.0 depinfo 1.5.4 diskcache 5.2.1 future 0.18.2 httpx 0.17.1 importlib_resources 5.3.0 numpy 1.20.1 optlang 1.5.2 pandas 1.2.3 pip 21.0.1 pydantic 1.8.1 python-libsbml 5.19.0 rich 9.13.0 ruamel.yaml 0.16.12 setuptools 49.6.0.post20210108 swiglpk 5.0.2 wheel 0.36.2

cdiener commented 2 years ago

Oh yeah this is an incorrect use of super(), good catch. Replacing it with super().__init__(formula, **kwargs) should fix it. I will send in a fix.