News for hackers. Stuff that matters.

xrudelis

Re:Show HN: Rust-Like Traits in Python on Sunday November 21, 2021 @06:21PM (#29300797)
It looks to me like the goals with typing.Protocol are for static type checking. Whereas this module is intended both for interfaces (much like ABCs) and implementation re-use (see Rust's "blanket implementations"). These Traits could definitely be used in type annotation, and maybe there's a way to use typing.Protocol with them to aid static type checking in Python. I haven't tried static type checking in Python yet, but it sounds promising!
Re:Show HN: Rust-Like Traits in Python on Sunday November 21, 2021 @05:29PM (#29300412)
I think these are all equally good. The Impl's name should never need to be referred to, so ultimately the choice should be based on what's easiest to read.

EDIT: actually, your examples wouldn't work as-is, since it would result in circular references (something Python isn't well-equipped to handle). Your target names would need to be strings instead of the actual class.

EDIT2: I have updated the code to allow for another syntax:

    class AnyImplNameIWant(MyTrait, metaclass=Impl, target="MyStruct"):
        ...
It would certainly be nicer if `MyStruct` didn't need to be a string of course. I really think these options are mostly down to taste, so I'll just have to trust that this alternative reads sufficiently more nicely.
Re:Show HN: Rust-Like Traits in Python on Sunday November 21, 2021 @05:07PM (#29300221)
That's right. The reason for this is that it's a lot of boilerplate if you were to require listing every relevant Impl block as a superclass of your struct. I also, as a bonus, like enforcing a consistent class naming style.
Re:Show HN: Rust-Like Traits in Python on Sunday November 21, 2021 @03:03PM (#29299212)
This is an idea I had while thinking about how flexible Python inheritance is. I decided to turn it into a weekend project, and now it is my first open-source package. I hope someone finds it useful!