On Sun, Jun 14, 2020 at 5:18 PM Stephen J. Turnbull
<[email protected]> wrote:
>
> Paul Moore writes:
>
>  > Personally, I find the version I wrote, that works in existing
>  > versions of Python, much more readable than your version, so you;d
>  > have a hard time persuading me that the new syntax is worth it :-)
>
> I think it's an interesting idea, although I'm with Alex on the color
> of the bikeshed.  Using Alex's 'in' and sets instead of sequences,
> consider
>
>     def food() in {2}:
>         return 2
>
>     def bar(n in {1, 2, 3}):
>         pass
>
>     def main():
>         bar(food())    # Paul doesn't think it tastes so great. :-)
>
> That could be checked by MyPy, without global dataflow analysis.
>
> Maybe
>
> def foo() -> {1, 2, 3}:
>     return 2
>
> is more readable, and probably just as implementable.
>

This definitely looks like a job for type hints, not new syntax. What
you're asking for here is that something be one of a specific set of
options, and that's really sounding like an enumeration to me.
Consider:

from enum import IntEnum

class Spam(IntEnum):
    foo = 1
    bar = 2
    quux = 3

def some_function(a: IntEnum, b):
    print("Got a:", a)

some_function(1, 2)
some_function(4, 2)

Unfortunately, MyPy (tested with version 0.78) doesn't accept integers
as valid parameters when IntEnum is expected, so this can't be done
seamlessly. But if you're doing something like this, you probably
should be working with the enum for other reasons anyway, so your code
would be more like this:

some_function(Spam.foo, 2)
some_function(..., 2)

and right there you can see that there's no way to get a Spam with a
value of 4. If you actually need to do it dynamically, you can do a
runtime cast:

some_function(Spam(1), 2)
some_function(Spam(4), 2)

And then you get the runtime ValueError like you were wanting.

ChrisA
_______________________________________________
Python-ideas mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3/lists/python-ideas.python.org/
Message archived at 
https://mail.python.org/archives/list/[email protected]/message/RHLAEXZCEKRWQOA4VPY52QWQA7UKRVO5/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to