coltonbh / qcio

A package for structured Quantum Chemistry data.
MIT License
4 stars 2 forks source link

[MODIFICATION] - Consider changing `CalcType.val` to `CalcType.VAL` #31

Open coltonbh opened 2 months ago

coltonbh commented 2 months ago

Convention usually suggests that constants, including Enums be CAPITALIZED. There's a bit of work to untangle historical use of lowercase enum vals and I'd want to support backwards compatibility for a while to not break people's code. I could do that with the following, though I'd need to untangle other places in the code that depend on the lower case convention:

from enum import EnumMeta

class CalcTypeMeta(EnumMeta):
    def __getattr__(cls, value):
        if value.upper() in cls.__members__:
            warnings.warn(
                f"The use of '{value}' is deprecated. Use '{value.upper()}' instead.",
                FutureWarning,
                stacklevel=4,  # may not always be correct
            )
            return getattr(cls, value.upper())
        raise AttributeError(f"{cls.__name__} has no attribute '{value}'")

class CalcType(str, Enum, metaclass=CalcTypeMeta):
    """The Calculation type."""

    ENERGY = "ENERGY"
    GRADIENT = "GRADIENT"
    HESSIAN = "HESSIAN"
    OPTIMIZATION = "OPTIMIZATION"
    TRANSITION_STATE = "TRANSITION_STATE"
    SMILES_TO_STRUCTURE = "SMILES_TO_STRUCTURE"

    @classmethod
    def _missing_(cls, value):
        if hasattr(cls, value.upper()):
            warnings.warn(
                f"The use of '{value}' is deprecated. Use '{value.upper()}' instead.",
                FutureWarning,
                stacklevel=4,  # may not always be correct
            )
            return getattr(cls, value.upper())
        return super()._missing_(value)

Then a test like so:

from qcio import CalcType

def test_calctype_backwards_compatibility():
    assert CalcType.energy == CalcType("energy") == CalcType.ENERGY == CalcType("ENERGY")
coltonbh commented 1 month ago

I also use the fact that the current lowercase enums return 'energeyorgradientfor their str method to make conversions betweenqcengineandqcop` easier.