Great timing! Last week I was trying to emulate a certain Rust example in
Python.
Rust has a way to implement families of classes without subclassing,
which I think could be a great addition to Python someday.  I'll explain
below.

Here is a Rust example (https://youtu.be/WDkv2cKOxx0?t=3795)
that demonstrates a way to implement classes without subclassing.

# Rust Code
enum Shape {
    Circle(f32),
    Square(f32),
    Rectangle(f32, f32)
}

impl Shape {
    fn area(self) -> f32 {
        match self {
            Shape::Circle(r) => 3.1 * r * r,
            Shape::Square(l) => l * l,
            Shape::Rectangle(l, w) => l * w
        }
    }
}

fn main () {
    let c = Shape::Circle(3.0);
    let s = Shape::Square(3.0);
    let r = Shape::Rectangle(3.0, 7.5);
    println!("○ {}", c.area());
    println!("□ {}", s.area());
    println!("▭ {}", r.area());
}

# Output
○ 27.899998
□ 9
▭ 22.5

The general idea is:
- declare classes that share a certain type
- extend common methods with a match-case style

That's it.  No sub-classing required.

I wondered if someday, can we do this in Python? This match-case proposal
seems to fit well in this example.

While I know this PEP does not focus on detailed applications,
does anyone believe we can achieve elegant class creation (sans
subclassing) with match-cases?


On Wed, Jun 24, 2020 at 2:04 PM Guido van Rossum <gu...@python.org> wrote:

> On Tue, Jun 23, 2020 at 11:27 PM Emily Bowman <silverback...@gmail.com>
> wrote:
> > I wonder if it's time to officially designate _ as a reserved name.
>
> Alas, it's too late for that. The i18n community uses _("message text") to
> mark translatable text. You may want to look into the gettext stdlib module.
>
> --
> --Guido van Rossum (python.org/~guido)
> *Pronouns: he/him **(why is my pronoun here?)*
> <http://feministing.com/2015/02/03/how-using-they-as-a-singular-pronoun-can-change-the-world/>
> _______________________________________________
> Python-Dev mailing list -- python-dev@python.org
> To unsubscribe send an email to python-dev-le...@python.org
> https://mail.python.org/mailman3/lists/python-dev.python.org/
> Message archived at
> https://mail.python.org/archives/list/python-dev@python.org/message/P6EKIKFP6MX2N2KVFFCF4XUVVMSJ6Q5B/
> Code of Conduct: http://python.org/psf/codeofconduct/
>
_______________________________________________
Python-Dev mailing list -- python-dev@python.org
To unsubscribe send an email to python-dev-le...@python.org
https://mail.python.org/mailman3/lists/python-dev.python.org/
Message archived at 
https://mail.python.org/archives/list/python-dev@python.org/message/ZUBYRUF4G5CWYQGX5Z3C57K2ZWEHRDWJ/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to