Closed andrewlee94 closed 1 year ago
One thought that did just cross my mind is that this could make it easier for us to document these things, as we could use Sphinx to autogenerate the docs based on the class of string constants,
I like the suggestion. Just make some classes that are like Enum but with string constants. Maybe we could have it so there is an easy method to check if a string const is defined in the class for argument validation in case people supply strings directly.
One of the things we have used in the past was a string-variant of Enum (see, e.g. https://github.com/Pyomo/pyomo/blob/2ad064be83da890f07fb1cd6109aca6ed4916c69/pyomo/core/expr/calculus/derivatives.py#L16-L27):
class BaseUnits(str, Enum):
mw = 'mw'
mass = 'mass'
amount = 'amount'
def __str__(self):
return self.value
This makes an enum that provides a lot of backwards compatibility with strings. In particular, the multiple inheritance and __str__
overload causes the following to work:
>>> 'mass' == BaseUnits.mass
True
>>> BaseUnits('mass')
<BaseUnits.mass: 'mass'>
Plus, printing out the unit produces the expected (old) string:
>>> print(BaseUnits.mass)
mass
I think the str, Enum inheritance is a good idea. I don't know exactly what @andrewlee94 is thinking with the docs, but it should make it easier to document for sure.
With #995 finally merged, I am going to call this done for now.
From a comment in #620:
@dangunter:
In the snippet of code above, there are actually two sets of magic string constants and I think that if we were to implement thus we would want to create separate classes for each:
property_base.py
)property_meta.py
)Do others have thoughts on this, and how important do we think this is?