Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

It seems to me that the problem with the first version is that it's stringly typed with `key: str | ActivationType`. There would be no issue if `key` was required to be an `ActivationType` with `key: ActivationType`, as you've done in the second version.

Code like the first version is usually someone is trying to make the API more convenient, but perhaps a better way, that's more in line with static type checking, would be to have a separate `activation_from_str(...)` function.

For a similar situation, I was thinking about doing something along these lines (somewhat Rust inspired), although the duplication of variant names in the from_str method isn't ideal:

    import enum
    import typing

    # stubs so this example is self-contained & runnable
    class Sigmoid: pass
    class Tanh: pass

    class ActivationType(enum.Enum):
        sigmoid = Sigmoid
        tanh = Tanh

    class Activation:

        @classmethod
        def new(cls, variant: ActivationType):
            return variant.value()

        @classmethod
        def from_str(cls, variant: typing.Literal["sigmoid", "tanh"]):
            return cls.new(ActivationType[variant])

    activation1 = Activation.new(ActivationType.sigmoid)
    activation2 = Activation.from_str("tanh")

Now, adding a new activation type just means adding it as a variant to ActivationType and adding a string to the literal list in from_str. Duplicating the name in from_str isn't great, but IMO it's better than having to add a new branch for each variant and the external API is nice too.


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: