[Python-ideas] Should nested classes in an Enum be Enum members?

Elazar elazarg at gmail.com
Wed Jun 27 16:06:24 EDT 2018


Yes, Ryan. I mean a way to express something like sealed classes in
scala/kotlin. The Enum class defines a finite region in which subclasses
can be defined, thus allows verifying that "elif" cases are exhaustive, for
exampe. It mostly helpful for static type checking, but it also helps
readability and is a natural way to describe ASTs.

class Expr(Enum):
    class BinOp(NamedTuple):  # ideally should subclass Expr
        left: Expr
        right: Expr
        op: str

    class UnOp(NamedTuple):
        operator: Expr
        operand: str

    ...

It's one of the (rejected) ideas here:
https://github.com/python/mypy/issues/2464

Not the best link out there but it explains:
https://antonioleiva.com/sealed-classes-kotlin/

Elazar


On Wed, Jun 27, 2018 at 12:49 PM Ryan Gonzalez <rymg19 at gmail.com> wrote:

> I *think* he's referring to something like this:
>
> class A(enum.Enum):
>     class Inner(NamedTuple):
>         ...
>
> isinstance(A.Inner(), A())  # True
>
> I *think* that's it.
>
>
>
> On June 27, 2018 2:26:23 PM Ethan Furman <ethan at stoneleaf.us> wrote:
>
> > On 06/27/2018 12:04 PM, Elazar wrote:
> >  > בתאריך יום ד׳, 27 ביוני 2018, 11:59, מאת Guido van Rossum:
> >
> >  >> Sounds to me really strange that the nested class would become a
> member.
> >  >> Probably because everything becomes a member unless it's a function
> >  >> (maybe decorated)?
> >  >
> >> People working with sum types might expect the instances of the nested
> >  > class to be instances of the enclosing class. So if the nested class
> is
> >  > a namedtuple, you get a sum type. The only problem is that there's no
> >  > way to express this subtype relationship in code.
> >
> > I have no idea what you just said.  :(  Is there a link you can share
> that
> > might explain it?
> >
> > --
> > ~Ethan~
> > _______________________________________________
> > Python-ideas mailing list
> > Python-ideas at python.org
> > https://mail.python.org/mailman/listinfo/python-ideas
> > Code of Conduct: http://python.org/psf/codeofconduct/
>
>
> _______________________________________________
> Python-ideas mailing list
> Python-ideas at python.org
> https://mail.python.org/mailman/listinfo/python-ideas
> Code of Conduct: http://python.org/psf/codeofconduct/
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-ideas/attachments/20180627/65b45ef0/attachment.html>


More information about the Python-ideas mailing list