python / mypy

Optional static typing for Python
https://www.mypy-lang.org/
Other
18.42k stars 2.82k forks source link

Lightweight Choice type #3874

Closed cmcaine closed 4 years ago

cmcaine commented 7 years ago

It's common practice in python to pass a string as a pseudo enum:

    def token(method='xkcd', entropy=70):
        """
        Generate a cryptographic token with a given entropy.

        """
        if method == 'xkcd':
            return xkcd(entropy)
        else:
            return alphanumeric(entropy)

I realise this is perhaps a little far out, but is mypy open to supporting an annotation that describes this?

I've just written a little module to generate argparse parsers by inspecting functions and defined my own Choice type:

from cli import Choice, cli

def token(method:Choice('xkcd', 'short')='xkcd', entropy:int=70):
    "Generate a cryptographic token with a given entropy."
    if method == 'xkcd':
    return xkcd(entropy)
    else:
    return alphanumeric(entropy)

cli(token)()

The version currently in the library no longer features this capability, but it's quite easy to write a version of Choice such that issubclass(Choice(1,2), Choice) and Choice(1,2)(1) == 1, which I thought was a neat interface.

ilevkivskyi commented 7 years ago

This is a valid feature request, but honestly we have lots of more important things to do now. IMO, you should really just use enum.Enum (or the backport if you are on an old version) in this situation. It is the "one obvious way to do it", and mypy provides special support for better type checking with enums.

cmcaine commented 7 years ago

Thanks for your response. I agree that Enum is the better way to do it :)