Better HN
topnewbestaskshowjobs
Log inSign up

xrudelis

41 karma · joined Nov 21, 2021 (5y ago) · 5 submissions

github.com/xrudelis
Submissions

comment 5y ago · link · parent

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!

comment 5y ago · link · parent

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.

comment 5y ago · link · parent

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.

comment 5y ago · link · parent

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!

5.

Show HN: Rust-Like Traits in Python(github.com ↗)

50 points · by xrudelis · 5y ago · 21 comments